package com.lancoo.ccas53.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.ImmutableMap;
import com.lancoo.ccas53.entity.Campus;
import com.lancoo.ccas53.entity.*;
import com.lancoo.ccas53.exception.BizException;
import com.lancoo.ccas53.mapper.MajorGradeMapper;
import com.lancoo.ccas53.mapper.TeachingClassStudentMapper;
import com.lancoo.ccas53.mapper.TeachingClassWeekMapper;
import com.lancoo.ccas53.pojo.common.PageInfo;
import com.lancoo.ccas53.pojo.dto.*;
import com.lancoo.ccas53.pojo.excel.*;
import com.lancoo.ccas53.pojo.response.basicPlatform.BaseCollege;
import com.lancoo.ccas53.pojo.response.basicPlatform.BaseStudent;
import com.lancoo.ccas53.pojo.vo.*;
import com.lancoo.ccas53.service.*;
import com.lancoo.ccas53.util.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotBlank;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 年级专业 服务实现类
 * </p>
 *
 * @author quin.song
 * @since 2024-05-20
 */
@Service
@Slf4j
public class MajorGradeServiceImpl extends ServiceImpl<MajorGradeMapper, MajorGrade> implements MajorGradeService {
    @Resource
    private CollComparatorUtil<MajorGrade> collComparatorUtil;
    @Resource
    @Lazy
    private YunBasicService yunBasicService;
    @Resource
    private CampusService campusService;
    @Resource
    private CollegeService collegeService;
    @Resource
    private MajorGradeMapper majorGradeMapper;
    @Resource
    private TeachingClassWeekMapper teachingClassWeekMapper;
    @Resource
    private TeachingClassStudentMapper teachingClassStudentMapper;
    @Resource
    private TeachingClassServiceImpl teachingClassService;
    @Resource
    private StudentService studentService;
    @Resource
    private PlanTeachingCourseService planTeachingCourseService;
    @Resource
    private PlanTeachingStudentService planTeachingStudentService;
    @Resource
    private TeachingClassStudentService teachingClassStudentService;
    @Resource
    private TeachingClassTeacherService teachingClassTeacherService;
    @Resource
    private RuleTimeProhibitService ruleTimeProhibitService;
    @Resource
    private RoomService roomService;
    @Resource
    private MajorGradeService majorGradeService;
    @Resource
    private TeachingClassWeekService teachingClassWeekService;
    @Resource
    private CourseWeekService courseWeekService;
    @Resource
    private SubClassService subClassService;
    @Resource
    private CssSelectCourseService selectCourseService;
    @Resource
    private TeacherService teacherService;
    @Resource
    private CourseService courseService;
    @Resource
    private SplitClassService splitClassService;
    @Resource
    private TaskInfoService taskInfoService;
    @Resource
    private PlanTeachingService planTeachingService;
    @Resource
    private CourseApplyService courseApplyService;
    @Value("${lancoo.schoolFlag}")
    private Integer schoolFlag;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void syncMajorGrade(Integer taskId, String schoolId) {
        //学院信息
        List<BaseCollege> baseCollege = yunBasicService.getCollege(schoolId);
        List<MajorGrade> majors = new ArrayList<>();
        //同步专业年级信息
        for (BaseCollege baseColl : baseCollege) {
            for (BaseCollege.SpecialitysDTO speciality : baseColl.getSpecialitys()) {
                for (BaseCollege.SpecialitysDTO.GradesDTO grade : speciality.getGrades()) {
                    majors.add(new MajorGrade()
                            .setTaskId(taskId)
                            .setGradeId(grade.getGradeID())
                            .setGradeName(grade.getGradeName())
                            .setBaseMajorId(speciality.getSpecialityID())
                            .setMajorName(speciality.getSpecialityName())
                            .setBaseCollegeId(baseColl.getCollegeID())
                            .setCollegeName(baseColl.getCollegeName())
                            .setIsCampusCross(1)
                            .setCreditLimit(30.0)
                            .setCourseLimit(10)
                            .setPreCreditLimit(30.0)
                            .setPreCourseLimit(10));
                }
            }
        }


        //获取数据库专业
        List<MajorGrade> majorList = this.list(new LambdaQueryWrapper<MajorGrade>().eq(MajorGrade::getTaskId, taskId));

        //插入数据库专业年级
        List<MajorGrade> insertList = collComparatorUtil.getAdded(majorList, majors);

        //填充默认校区
        List<Campus> campusList = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list();
        if (CollUtil.isNotEmpty(campusList)) {
            insertList.forEach(o -> {
                o.setCampusId(campusList.get(0).getCampusId());
                o.setCampusName(campusList.get(0).getCampusName());

            });
        }

        List<MajorGrade> deleteMajorGradeList = collComparatorUtil.getDeleted(majorList, majors);
        List<Long> deleteIds = deleteMajorGradeList.stream().map(MajorGrade::getMajorGradeId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(deleteIds)) {
            this.removeBatchByIds(deleteIds);
        }
        if (CollUtil.isNotEmpty(insertList)) {
            majorGradeMapper.addBatch(insertList);
        }
        //同步学院信息
        collegeService.syncColleges(taskId, baseCollege);

    }

    @Override
    public List<MajorVo> getMajor(Integer taskId, String baseCollegeId) {
        return majorGradeMapper.getMajor(taskId, baseCollegeId);
    }

    @Override
    public List<GradeVo> getGrade(Integer taskId, String baseCollegeId) {
        List<GradeVo> gradeList = majorGradeMapper.getGrade(taskId, baseCollegeId);
        return gradeList.stream().sorted(Comparator.comparing(GradeVo::getGradeName)).collect(Collectors.toList());
    }

    @Override
    public List<CollegeTree> getMajorGradeTree(Integer taskId, String keyword, Integer studyNature) {
        List<CollegeTree> result = new ArrayList<>();
        List<MajorGrade> list = this.lambdaQuery().eq(MajorGrade::getTaskId, taskId).like(StringUtils.isNotBlank(keyword), MajorGrade::getMajorName, keyword).list();
        List<String> collegeList = list.stream().map(MajorGrade::getCollegeName).distinct().collect(Collectors.toList());
        List<PlanTeaching> planTeachingList = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId).eq(PlanTeaching::getStudyNature, studyNature).list();
        for (String college : collegeList
        ) {
            int majorSum = 0;
            CollegeTree collegeTree = new CollegeTree();
            collegeTree.setCollegeName(college);
            String collegeId = list.stream().filter(a -> a.getCollegeName().equals(college)).findFirst().get().getBaseCollegeId();
            collegeTree.setCollegeId(collegeId);
            List<GradeTree> gradeTreeList = new ArrayList<>();
            List<MajorGrade> list1 = this.lambdaQuery().eq(MajorGrade::getCollegeName, college)
                    .eq(MajorGrade::getTaskId, taskId)
                    .like(StringUtils.isNotBlank(keyword), MajorGrade::getMajorName, keyword).list();
            List<String> gradeList = list1.stream().map(MajorGrade::getGradeName).distinct().collect(Collectors.toList());
            Collections.sort(gradeList);
            for (String grade : gradeList
            ) {
                GradeTree gradeTree = new GradeTree();
                gradeTree.setGradeName(grade);
                String gradeId = list1.stream().filter(a -> a.getCollegeName().equals(college) && a.getGradeName().equals(grade)).findFirst().get().getGradeId();
                gradeTree.setGradeId(gradeId);
                List<MajorGrade> list2 = this.lambdaQuery().eq(MajorGrade::getTaskId, taskId)
                        .eq(MajorGrade::getGradeName, grade).eq(MajorGrade::getCollegeName, college)
                        .like(StringUtils.isNotBlank(keyword), MajorGrade::getMajorName, keyword).list();
                List<String> majorList = list2.stream().map(MajorGrade::getMajorName).distinct().collect(Collectors.toList());
                List<MajorTree> majorTreeList = new ArrayList<>();
                for (String major : majorList
                ) {
                    MajorTree majorTree = new MajorTree();
                    majorTree.setMajorName(major);
                    String majorId = list2.stream().filter(a -> a.getCollegeName().equals(college) && a.getGradeName().equals(grade) && a.getMajorName().equals(major)).findFirst().get().getBaseMajorId();
                    majorTree.setMajorId(majorId);
                    //不存在培养计划则删除该专业
                    List<PlanTeaching> planTeachings = planTeachingList.stream()
                            .filter(a -> a.getBaseCollegeId().equals(collegeTree.getCollegeId())
                                    && a.getGradeId().equals(gradeTree.getGradeId())
                                    && a.getBaseMajorId().equals(majorTree.getMajorId())
                            ).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(planTeachings)) {
                        majorTreeList.add(majorTree);
                    }
                }
                gradeTree.setMajorList(majorTreeList);
                gradeTree.setMajorCount(majorTreeList.size());
                if (CollUtil.isNotEmpty(majorTreeList)) {
                    gradeTreeList.add(gradeTree);
                }
                majorSum += majorTreeList.size();
            }
            collegeTree.setGradeList(gradeTreeList);
            collegeTree.setMajorSum(majorSum);
            if (CollUtil.isNotEmpty(gradeTreeList)) {
                result.add(collegeTree);
            }
        }
        return result;
    }

    @Override
    public Boolean setMajorGrade(MajorGradeInput majorGradeInput) {
        this.lambdaUpdate()
                .set(majorGradeInput.getCampusId() != null, MajorGrade::getCampusId, majorGradeInput.getCampusId())
                .set(StrUtil.isNotBlank(majorGradeInput.getCampusName()), MajorGrade::getCampusName, majorGradeInput.getCampusName())
                .set(majorGradeInput.getIsCampusCross() != null, MajorGrade::getIsCampusCross, majorGradeInput.getIsCampusCross())
                .set(majorGradeInput.getCreditLimit() != null, MajorGrade::getCreditLimit, majorGradeInput.getCreditLimit())
                .set(majorGradeInput.getCourseLimit() != null, MajorGrade::getCourseLimit, majorGradeInput.getCourseLimit())
                .set(majorGradeInput.getPreCreditLimit() != null, MajorGrade::getPreCreditLimit, majorGradeInput.getPreCreditLimit())
                .set(majorGradeInput.getPreCourseLimit() != null, MajorGrade::getPreCourseLimit, majorGradeInput.getPreCourseLimit())
                .set(majorGradeInput.getBaseSchemeId() != null, MajorGrade::getBaseSchemeId, majorGradeInput.getBaseSchemeId())
                .set(majorGradeInput.getBaseSchemeName() != null, MajorGrade::getBaseSchemeName, majorGradeInput.getBaseSchemeName())
                .in(MajorGrade::getMajorGradeId, majorGradeInput.getMajorGradeIds())
                .update();
        return true;
    }

    @Override
    public Boolean clearMajorGrade(Integer taskId) {
        List<MajorGrade> data = this.lambdaQuery().eq(MajorGrade::getTaskId, taskId).list();
        Campus campus = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list().get(0);
        for (MajorGrade item : data) {
            item.setIsCampusCross(1);
            item.setCampusId(campus.getCampusId());
            item.setCampusName(campus.getCampusName());
            majorGradeMapper.updateById(item);
        }
        return true;
    }


    @Override
    public void exportStudentInformationSettings(HttpServletResponse response, Integer taskId, Integer campusId, String baseCollegeId, String baseMajorId, String gradeId, String keyword, Integer isCampusCross, Integer currentPage, Integer pageSize) {


        List<ExcelStudentInfo> excelStudentInfos = new ArrayList<>();

        Page<MajorGrade> majorGradePage = this.lambdaQuery()
                .eq(MajorGrade::getTaskId, taskId)
                .eq(campusId != null, MajorGrade::getCampusId, campusId)
                .eq(StrUtil.isNotBlank(baseCollegeId), MajorGrade::getBaseCollegeId, baseCollegeId)
                .eq(StrUtil.isNotBlank(baseMajorId), MajorGrade::getBaseMajorId, baseMajorId)
                .eq(StrUtil.isNotBlank(gradeId), MajorGrade::getGradeId, gradeId)
                .like(StrUtil.isNotBlank(keyword), MajorGrade::getMajorName, keyword)
                .eq(isCampusCross != null && isCampusCross != 0, MajorGrade::getIsCampusCross, isCampusCross)
                .page(new Page<>(1, -1));


        List<Student> students = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();

        TaskInfo taskInfo = taskInfoService.getById(taskId);

        List<Campus> campusList = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list();

        List<MajorVo> major = this.getMajor(taskId, null);


        Campus campus = new Campus();
        if (ObjUtil.isNotNull(campusId)) {
            List<Campus> campuses = campusList.stream().filter(p -> p.getCampusId().equals(campusId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(campuses)) {
                campus = campuses.get(0);
            }
        }


        MajorVo majorVo = new MajorVo();
        if (StringUtils.isNotBlank(baseMajorId)) {
            List<MajorVo> majorVos = major.stream().filter(p -> p.getBaseMajorId()
                    .equals(p.getBaseMajorId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(majorVos)) {
                majorVo = majorVos.get(0);

            }
        }


        List<MajorGrade> records = majorGradePage.getRecords();

        MajorGrade majorGrade = new MajorGrade();
        if (CollUtil.isNotEmpty(records)) {
            majorGrade = records.get(0);
        }

        //构建标题
        String title = " {} {}学生信息设置导出" + "\n" + "校区:{}" + "\n" + "院系:{}" + "\n" + "专业:{}" + "\n" + "年级:{}";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                , ObjUtil.isNull(campusId) ? "全部" : campus.getCampusName(),
                StringUtils.isNotBlank(baseCollegeId) ? majorGrade.getCollegeName() : "全部院系",
                StringUtils.isNotBlank(baseMajorId) ? majorVo.getMajorName() : "全部专业",
                StringUtils.isNotBlank(gradeId) ? majorGrade.getGradeName() : "全部年级");


        records.forEach(o -> {
            List<Student> studentList = students.stream().filter(p -> p.getBaseCollegeId().equals(o.getBaseCollegeId()) && p.getGradeId().equals(o.getGradeId()) && p.getMajorId().equals(o.getBaseMajorId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(studentList)) {
                studentList.forEach(s -> {
                    ExcelStudentInfo excelStudentInfo = new ExcelStudentInfo();
                    excelStudentInfo.setStudentName(s.getStudentName());
                    excelStudentInfo.setClassName(s.getClassName());
                    excelStudentInfo.setBaseStudentId(s.getBaseStudentId());
                    excelStudentInfo.setSexCode(s.getSexCode());
                    excelStudentInfo.setCollegeName(o.getCollegeName());
                    excelStudentInfo.setGradeName(o.getGradeName());
                    excelStudentInfo.setMajorName(o.getMajorName());
                    excelStudentInfo.setCampusName(o.getCampusName());
                    excelStudentInfos.add(excelStudentInfo);
                });
            }
        });


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelStudentInfos,
                format,
                "学生信息设置",
                ExcelStudentInfo.class,
                "学生信息设置导出表" + time + ".xls", response);


    }


    @Override
    public void exportTeacherInformationSettings(HttpServletResponse response, Integer taskId, Integer campusId, String baseCollegeId, Integer identity, Integer isCampusCross, String keyword, Long courseId, Integer currentPage, Integer pageSize) {

        List<ExcelTeacherInfo> excelTeacherInfos = new ArrayList<>();

        Page<TeacherCourseVo> page = new Page<>(1, -1);

        PageInfo<TeacherCourseVo> teacherCourseList = teacherService.getTeacherCourseList(page, taskId, campusId, baseCollegeId, identity, isCampusCross, keyword, courseId);

        List<TeacherCourseVo> list = teacherCourseList.getList();

        list.forEach(o -> {
            ExcelTeacherInfo excelTeacherInfo = new ExcelTeacherInfo();
            excelTeacherInfo.setTeacherNo(o.getBaseTeacherId());
            excelTeacherInfo.setTeacherName(o.getTeacherName());
            excelTeacherInfo.setCollegeName(o.getCollegeName());
            excelTeacherInfo.setCourseName(o.getCourseNames());
            excelTeacherInfo.setIdentyName(o.getIdentity() == 1 ? "任课教师" : "助教教师");
            excelTeacherInfos.add(excelTeacherInfo);
        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        List<Campus> campusList = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list();


        Campus campus = new Campus();
        if (ObjUtil.isNotNull(campusId)) {
            List<Campus> campuses = campusList.stream().filter(p -> p.getCampusId().equals(campusId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(campuses)) {
                campus = campuses.get(0);
            }
        }


        Course course = new Course();
        List<Course> courseList = courseService.getCourseList(taskId, null, null, null, null, null, null, null);
        if (ObjUtil.isNotNull(courseId)) {
            List<Course> courseList1 = courseList.stream().filter(p -> p.getCourseId().equals(courseId)).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(courseList1)) {
                course = courseList1.get(0);
            }
        }

        String collegeName = "";
        if (CollUtil.isNotEmpty(list)) {
            TeacherCourseVo teacherCourseVo = list.get(0);
            collegeName = teacherCourseVo.getCollegeName();
        }

        //构建标题
        String title = " {} {}教师信息设置导出" + "\n" + "校区:{}" + "\n" + "院系:{}" + "\n" + "课程:{}" + "\n" + "任课教师:{}";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                , ObjUtil.isNull(campusId) ? "全部" : campus.getCampusName()
                , StringUtils.isBlank(baseCollegeId) ? "全部院系" : collegeName,
                ObjUtil.isNotNull(courseId) ? course.getCourseName() : "全部课程",
                ObjUtil.isNull(identity) ? "全部身份" : (identity == 1 ? "任课教师" : "助教教师"));

        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelTeacherInfos,
                format,
                "教师设置导出",
                ExcelTeacherInfo.class,
                "教师设置导出表" + time + ".xls", response);

    }


//    @Override
//    public void exportOfTheStartPlan(HttpServletResponse response, Integer taskId, String courseName, String collegeName, String gradeName, String majorName, String courseType, String courseNature, String credit,
//    String totalNum, String lectureHour, String experimentalHour, String computerHour, String otherHour, String state) {
//
//
//        CourseVo courseVo = new CourseVo();
//
//        courseVo.setCurrentPage(1);
//        courseVo.setPageSize(100000);
//
//        CourseAndApplyDto courseAndApply = planTeachingService.getCourseAndApply(courseVo, taskId);
//
//        //构造列名
//        List<ExcelExportEntity> entityList = new ArrayList<>();
//
//
//        if (StringUtils.isNotBlank(courseName)) {
//            ExcelExportEntity entity = new ExcelExportEntity("课程名称编号", "courseName");
//            entityList.add(entity);
//        }
//
//        if (StringUtils.isNotBlank(collegeName)) {
//            ExcelExportEntity entity = new ExcelExportEntity("开课单位", "collegeName");
//            entityList.add(entity);
//        }
//
//        if (StringUtils.isNotBlank(gradeName)) {
//            ExcelExportEntity entity = new ExcelExportEntity("年级", "gradeName");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(majorName)) {
//            ExcelExportEntity entity = new ExcelExportEntity("专业", "majorName");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(courseType)) {
//            ExcelExportEntity entity = new ExcelExportEntity("课程类别", "courseType");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(courseNature)) {
//            ExcelExportEntity entity = new ExcelExportEntity("课程性质", "courseNature");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(totalNum)) {
//            ExcelExportEntity entity = new ExcelExportEntity("总学时", "totalNum");
//            entityList.add(entity);
//        }
//
//        if (StringUtils.isNotBlank(credit)) {
//            ExcelExportEntity entity = new ExcelExportEntity("学分", "credit");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(lectureHour)) {
//            ExcelExportEntity entity = new ExcelExportEntity("讲授学时", "lectureHour");
//            entityList.add(entity);
//        }
//
//        if (StringUtils.isNotBlank(computerHour)) {
//            ExcelExportEntity entity = new ExcelExportEntity("上机学时", "computerHour");
//            entityList.add(entity);
//        }
//
//        if (StringUtils.isNotBlank(experimentalHour)) {
//            ExcelExportEntity entity = new ExcelExportEntity("实验学时", "experimentalHour");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(otherHour)) {
//            ExcelExportEntity entity = new ExcelExportEntity("其他学时", "otherHour");
//            entityList.add(entity);
//        }
//
//
//        if (StringUtils.isNotBlank(state)) {
//            ExcelExportEntity entity = new ExcelExportEntity("状态说明", "state");
//            entityList.add(entity);
//        }
//
//
//        TaskInfo taskInfo = taskInfoService.getById(taskId);
//
//        String title = " {} {}确认开课计划导出";
//        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());
//
//        ExportParams params = new ExportParams(format, "确认开课计划");
//
//        List<CourseVo> courseVoList = courseAndApply.getCourseVoList();
//        List<Map<String, Object>> resultList = new ArrayList<>();
//        courseVoList.forEach(o -> {
//            Map<String, Object> rowMap = new HashMap<>();
//            rowMap.put("courseName", o.getCourseName());
//            rowMap.put("collegeName", o.getCollegeName());
//            rowMap.put("gradeName", o.getGradeName());
//            rowMap.put("majorName", o.getMajorName());
//            rowMap.put("courseType", o.getCourseType());
//            rowMap.put("courseNature", o.getCourseNature());
//            rowMap.put("totalNum", o.getTeachWeekCount());
//            rowMap.put("credit", o.getCredit());
//            rowMap.put("lectureHour", o.getLectureHour());
//            rowMap.put("computerHour", o.getComputerHour());
//            rowMap.put("experimentalHour", o.getExperimentalHour());
//            rowMap.put("otherHour", o.getOtherHour());
//            rowMap.put("state", o.getReviewComment());
//            resultList.add(rowMap);
//        });
//
//
//        params.setTitle(format);
//        params.setSheetName("确认开课计划");
//
//        //生成要导出的数据
//        Workbook workbook = ExcelExportUtil.exportExcel(params, entityList, resultList);
//
//        if (workbook != null) {
//            downLoadExcel("题目", response, workbook);
//        }
//    }


    @Override
    public void exportSetThePreSelectedCourseRotation(HttpServletResponse response, Integer taskId, Optional<Integer> type) {

        List<ExcelPreSelect> excelPreSelects = new ArrayList<>();
        List<RoundListDto> roundList = selectCourseService.getRoundList(type, taskId);

        roundList.forEach(o -> {
            ExcelPreSelect excelPreSelect = new ExcelPreSelect();

            excelPreSelect.setSelectRound(o.getRoundName());

            excelPreSelect.setCourseSelectionAuthority(o.getSelectAuthority() == 1 ? "可退/可选" : (o.getSelectAuthority() == 2 ? "仅可选" : "仅可退"));

            excelPreSelect.setStartTime(o.getBeginTime());

            excelPreSelect.setEndTime(o.getEndTime());

            excelPreSelect.setSelectNum(o.getStudentNum());

            List<CssStudentRange> studentRange = o.getStudentRange();

            Map<String, List<CssStudentRange>> collegeMap = studentRange.stream().collect(Collectors.groupingBy(CssStudentRange::getBaseCollegeId));

            List<ExcelCollegeSelectDto> excelCollegeSelectDtos = new ArrayList<>();
            collegeMap.forEach((key, value) -> {
                CssStudentRange cssStudentRange = value.get(0);
                ExcelCollegeSelectDto excelCollegeSelectDto = new ExcelCollegeSelectDto();
                excelCollegeSelectDto.setSelectCollege(cssStudentRange.getCollegeName());
                String gradeName = value.stream().map(CssStudentRange::getGradeName).distinct().collect(Collectors.joining(","));
                excelCollegeSelectDto.setSelectGradeName(gradeName);
                excelCollegeSelectDtos.add(excelCollegeSelectDto);
            });

            excelPreSelect.setCollegeSelectDtos(excelCollegeSelectDtos);

            excelPreSelect.setSelectState(o.getIsEnable() == 0 ? "未开始" : "选课中");

            excelPreSelects.add(excelPreSelect);

        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}预选课信息导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());

        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelPreSelects,
                format,
                "预选课轮次",
                ExcelPreSelect.class,
                "设置预选课轮次导出" + time + ".xls", response);
    }

    @Override
    public void exportThePreselectionResult(HttpServletResponse response, Integer taskId, String courseName, String collegeName, String courseType, String courseNatureName, String selectStudentNums,
                                            String state, String isCourseState, String baseCollegeId, String courseTypeId, Optional<Integer> courseNature, String keyword, Optional<Integer> isEnable, Optional<Integer> isAchieveOpen, Integer pageSize, Integer currentPage) {


        //构造列名
        List<ExcelExportEntity> entityList = new ArrayList<>();


        if (ObjUtil.isNotNull(courseName)) {
            ExcelExportEntity entity = new ExcelExportEntity("课程", "courseName");
            entityList.add(entity);
        }

        if (StringUtils.isNotBlank(collegeName)) {
            ExcelExportEntity entity = new ExcelExportEntity("开课单位", "collegeName");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(courseType)) {
            ExcelExportEntity entity = new ExcelExportEntity("课程类别", "courseType");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(courseNatureName)) {
            ExcelExportEntity entity = new ExcelExportEntity("课程性质", "courseNature");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(selectStudentNums)) {
            ExcelExportEntity entity = new ExcelExportEntity("已选人数", "selectStudentNums");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(state)) {
            ExcelExportEntity entity = new ExcelExportEntity("说明", "state");
            entityList.add(entity);
        }

        if (StringUtils.isNotBlank(isCourseState)) {
            ExcelExportEntity entity = new ExcelExportEntity("开课状态", "isCourseState");
            entityList.add(entity);
        }

        ExportParams params = new ExportParams();

        ResultDto<PreResultDto> preResultList = selectCourseService.getPreResultList(baseCollegeId, courseTypeId, courseNature, keyword, isEnable, isAchieveOpen, 10000, 1, taskId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        preResultList.getList().forEach(o -> {
            Map<String, Object> rowMap = new HashMap<>();
            rowMap.put("courseName", o.getCourseName());
            rowMap.put("collegeName", o.getCollegeName());
            rowMap.put("courseType", o.getCourseType());
            rowMap.put("courseNature", o.getCourseNature() == 1 ? "必修" : "选修");
            rowMap.put("selectStudentNums", o.getStudentNum());
            rowMap.put("isCourseState", o.getIsEnable() == 0 ? "取消开班" : "正常开班");
            rowMap.put("state", o.getDescription());
            resultList.add(rowMap);
        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {}预选课结果导出 {}学期";
        String format = StrUtil.format(title, taskInfo.getSchoolName(), taskInfo.getTerm());


        params.setTitle(format);
        params.setSheetName("预选课结果");
        //生成要导出的数据
        Workbook workbook = ExcelExportUtil.exportExcel(params, entityList, resultList);

        if (workbook != null) {
            downLoadExcel(format, response, workbook);
        }

    }


    @Override
    public void exportPreSelectedCourseLogs(HttpServletResponse response, Integer taskId, Long roundId, String baseCollegeId, String gradeId, String classId, Long courseId, String startDateTime, String endDateTime, String keyword, Integer pageSize, Integer currentPage) {


        List<ExcelPreSelectCourseLog> excelPreSelectCourseLogs = new ArrayList<>();
        ResultDto<PreLogsDto> preLogs = selectCourseService.getPreLogs(roundId, baseCollegeId, gradeId, classId, courseId, startDateTime, endDateTime, keyword, 10000, 1, taskId);


        Map<Long, Course> courseMap = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list().stream().collect(Collectors.toMap(Course::getCourseId, Function.identity()));

        preLogs.getList().forEach(o -> {
            ExcelPreSelectCourseLog excelPreSelectCourseLog = new ExcelPreSelectCourseLog();
            excelPreSelectCourseLog.setStudentName(o.getStudentName() + "(" + o.getBaseStudentId() + ")");
            excelPreSelectCourseLog.setCollegeName(o.getCollegeName());
            excelPreSelectCourseLog.setGradeName(o.getGradeName());

            excelPreSelectCourseLog.setClassName(o.getClassName());

            excelPreSelectCourseLog.setOption(o.getFlag() == 1 ? "选课" : (o.getFlag() == 2 ? "退选" : "管理员移除"));

            excelPreSelectCourseLog.setCourseName(courseMap.get(o.getCourseId()).getCourseName() + "(" + courseMap.get(o.getCourseId()).getBaseCourseId() + ")");

            excelPreSelectCourseLog.setSelectTime(o.getCreatedTime());

            excelPreSelectCourseLogs.add(excelPreSelectCourseLog);

        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}预选课信息日志导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelPreSelectCourseLogs,
                format,
                "预选课日志导出",
                ExcelPreSelectCourseLog.class,
                "预选课日志导出" + time + ".xls", response);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importStudentInformationSettings(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {

        List<ExcelStudentDto> excelStudentDtos = this.readStudentList(file);

        TaskInfo taskInfo = taskInfoService.getById(taskId);


        Long index = 3L;
        for (ExcelStudentDto excelTeachingActivity : excelStudentDtos) {
            excelTeachingActivity.setId(index);
            index++;
        }

        List<Campus> campusList = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list();

        Map<String, Campus> campusMap1 = campusList.stream().collect(Collectors.toMap(Campus::getCampusName, Function.identity(), (o1, o2) -> o1));


        List<Student> studentList = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();

        List<BaseStudent> students = yunBasicService.getStudent(taskInfo.getSchoolId());

        Map<String, List<BaseStudent>> gradeMap = students.stream().collect(Collectors.groupingBy(BaseStudent::getGradeName));
        Map<String, List<BaseStudent>> majorMap = students.stream().collect(Collectors.groupingBy(BaseStudent::getSpecialityName));
        Map<String, List<BaseStudent>> collegeMap = students.stream().collect(Collectors.groupingBy(BaseStudent::getCollegeName));
        Map<String, List<BaseStudent>> classMap = students.stream().collect(Collectors.groupingBy(BaseStudent::getClassName));


        List<Student> students1 = new ArrayList<>();


        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();

        Map<String, List<ExcelStudentDto>> stuClassMap = excelStudentDtos.stream().collect(Collectors.groupingBy(ExcelStudentDto::getClassName));

        stuClassMap.forEach((key, value) -> {
            List<BaseStudent> baseStudents = classMap.get(key);
            if (CollUtil.isEmpty(baseStudents)) {
                value.forEach(o -> {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(o.getId());
                    errorExcelVo.setErrorMsg("第" + o.getId() + "行" + o.getClassName() + "行政班基础平台未录入");
                    errorExcelVos.add(errorExcelVo);
                });
            }

            value.forEach(o -> {
                List<BaseStudent> baseStudents1 = gradeMap.get(o.getGradeName());
                if (CollUtil.isEmpty(baseStudents1)) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(o.getId());
                    errorExcelVo.setErrorMsg("第" + o.getId() + "行" + o.getGradeName() + "年级基础平台未录入");
                    errorExcelVos.add(errorExcelVo);
                }


                List<BaseStudent> baseStudents2 = collegeMap.get(o.getCollegeName());
                if (CollUtil.isEmpty(baseStudents2)) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(o.getId());
                    errorExcelVo.setErrorMsg("第" + o.getId() + "行" + o.getCollegeName() + "院系基础平台未录入");
                    errorExcelVos.add(errorExcelVo);
                }


                List<BaseStudent> baseStudents3 = majorMap.get(o.getMajorName());
                if (CollUtil.isEmpty(baseStudents3)) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(o.getId());
                    errorExcelVo.setErrorMsg("第" + o.getId() + "行" + o.getMajorName() + "专业基础平台未录入");
                    errorExcelVos.add(errorExcelVo);
                }

                if (StringUtils.isNotBlank(o.getCampusName()) && !campusMap1.containsKey(o.getCampusName().trim())) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(o.getId());
                    errorExcelVo.setErrorMsg(o.getCampusName() + "校区不存在");
                    errorExcelVos.add(errorExcelVo);
                }
            });
        });

        Integer errorExcelVos3 = errorExcelVos.size();

        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入学生信息错误",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入错误信息" + time + ".xls", response);
            throw new BizException("导入学生信息错误");
        }

        if (errorExcelVos3 == 0) {
            //导入学生信息
            List<Long> studentIds = new ArrayList<>();

            excelStudentDtos.forEach(o -> {

                Student student2 = studentList.stream().filter(p -> p.getBaseStudentId().equals(o.getBaseStudentId())).findFirst().orElse(null);
                if (ObjUtil.isNotNull(student2)) {
                    studentIds.add(student2.getStudentId());
                    BaseStudent grade = gradeMap.get(o.getGradeName()).get(0);
                    BaseStudent major = majorMap.get(o.getMajorName()).get(0);
                    BaseStudent college = collegeMap.get(o.getCollegeName()).get(0);
                    List<BaseStudent> students2 = classMap.get(o.getClassName());

                    Student student = new Student();

                    student.setTaskId(taskId);
                    student.setBaseStudentId(o.getBaseStudentId());
                    student.setStudentName(o.getStudentName());
                    if (CollUtil.isNotEmpty(students2)) {
                        BaseStudent student1 = students2.get(0);
                        student.setClassId(student1.getClassID());
                    }
                    student.setClassName(o.getClassName());
                    student.setMajorId(major.getSpecialityID());
                    student.setMajorName(major.getSpecialityName());
                    student.setCollegeName(college.getCollegeName());
                    student.setBaseCollegeId(college.getCollegeID());
                    student.setSexCode(o.getSexCode());
                    student.setGradeId(grade.getGradeID());
                    student.setGradeName(grade.getGradeName());
                    student.setSelectionScope(1);
                    student.setPreCreditLimit(30.0);
                    student.setCourseLimit(10);
                    students1.add(student);
                } else {
                    BaseStudent grade = gradeMap.get(o.getGradeName()).get(0);
                    BaseStudent major = majorMap.get(o.getMajorName()).get(0);
                    BaseStudent college = collegeMap.get(o.getCollegeName()).get(0);
                    List<BaseStudent> students2 = classMap.get(o.getClassName());
                    Student student = new Student();
                    student.setTaskId(taskId);
                    student.setBaseStudentId(o.getBaseStudentId());
                    student.setStudentName(o.getStudentName());
                    if (CollUtil.isNotEmpty(students2)) {
                        BaseStudent student1 = students2.get(0);
                        student.setClassId(student1.getClassID());
                    }
                    student.setClassName(o.getClassName());
                    student.setMajorId(major.getSpecialityID());
                    student.setMajorName(major.getSpecialityName());
                    student.setCollegeName(college.getCollegeName());
                    student.setBaseCollegeId(college.getCollegeID());
                    student.setSexCode(o.getSexCode());
                    student.setGradeId(grade.getGradeID());
                    student.setGradeName(grade.getGradeName());
                    student.setSelectionScope(1);
                    student.setPreCreditLimit(30.0);
                    student.setCourseLimit(10);
                    students1.add(student);
                }
            });

            if (CollUtil.isNotEmpty(studentIds)) {
                studentService.lambdaUpdate().eq(Student::getTaskId, taskId).in(Student::getStudentId, studentIds).remove();
            }

            if (CollUtil.isNotEmpty(students1)) {
                studentService.saveOrUpdateBatch(students1);
            }


            //更新院系

            List<MajorGrade> majorGrades = majorGradeMapper.selectList(new LambdaQueryWrapper<MajorGrade>().eq(MajorGrade::getTaskId, taskId));

            List<Student> studentList1 = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();

            List<MajorGrade> majorGradeList = new ArrayList<>();


            Map<String, List<Student>> stuCollegeMap = studentList1.stream().collect(Collectors.groupingBy(Student::getBaseCollegeId));


            stuCollegeMap.forEach((key, value) -> {
                Map<String, List<Student>> stuMajorMap = value.stream().collect(Collectors.groupingBy(Student::getMajorId));
                stuMajorMap.forEach((k, v) -> {
                    Map<String, List<Student>> stuGradeMap = v.stream().collect(Collectors.groupingBy(Student::getGradeId));
                    stuGradeMap.forEach((g, f) -> {
                        MajorGrade majorGrade = majorGrades.stream().filter(p -> p.getBaseCollegeId().equals(key) && p.getBaseMajorId().equals(k) && p.getGradeId().equals(g)).findFirst().orElse(null);
                        if (ObjUtil.isNull(majorGrade)) {
                            Student student = f.get(0);
                            MajorGrade majorGrade1 = new MajorGrade();
                            majorGrade1.setBaseCollegeId(key);
                            majorGrade1.setCollegeName(student.getCollegeName());
                            majorGrade1.setBaseMajorId(student.getMajorId());
                            majorGrade1.setMajorName(student.getMajorName());
                            majorGrade1.setGradeId(student.getGradeId());
                            majorGrade1.setGradeName(student.getGradeName());
                            majorGrade1.setTaskId(taskId);
                            List<ExcelStudentDto> studentDtos = excelStudentDtos.stream().filter(p -> p.getCollegeName().equals(student.getCollegeName())
                                    && p.getMajorName().equals(student.getMajorName()) && p.getGradeName().equals(student.getGradeName())).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(studentDtos)) {
                                ExcelStudentDto excelStudentDto = studentDtos.get(0);
                                majorGrade1.setCampusId(StringUtils.isNotBlank(excelStudentDto.getCampusName()) ? campusMap1.get(excelStudentDto.getCampusName()).getCampusId() : null);
                                majorGrade1.setCampusName(StringUtils.isNotBlank(excelStudentDto.getClassName()) ? campusMap1.get(excelStudentDto.getCampusName()).getCampusName() : "");
                            } else {
                                Campus campus = campusList.get(0);
                                majorGrade1.setCampusId(campus.getCampusId());
                                majorGrade1.setCampusName(campus.getCampusName());
                            }
                            majorGrade1.setIsCampusCross(1);
                            majorGradeList.add(majorGrade1);
                        } else {
                            Student student = f.get(0);
                            List<ExcelStudentDto> studentDtos = excelStudentDtos.stream().filter(p -> p.getCollegeName().equals(student.getCollegeName())
                                    && p.getMajorName().equals(student.getMajorName()) && p.getGradeName().equals(student.getGradeName())).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(studentDtos)) {
                                ExcelStudentDto excelStudentDto = studentDtos.get(0);
                                majorGrade.setCampusId(StringUtils.isNotBlank(excelStudentDto.getCampusName()) ? campusMap1.get(excelStudentDto.getCampusName()).getCampusId() : null);
                                majorGrade.setCampusName(StringUtils.isNotBlank(excelStudentDto.getCampusName()) ? campusMap1.get(excelStudentDto.getCampusName()).getCampusName() : "");
                            }
                            majorGradeList.add(majorGrade);
                        }
                    });
                });
            });

            if (CollUtil.isNotEmpty(majorGradeList)) {
                this.saveOrUpdateBatch(majorGradeList);
            }
        }


    }

    private List<ExcelStudentDto> readStudentList(MultipartFile file) {
        List<ExcelStudentDto> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "学生名称", "学生id", "性别", "年级", "所属院系", "专业", "行政班名称", "上课校区");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("学生名称", "studentName");
            reader.addHeaderAlias("学生id", "baseStudentId");
            reader.addHeaderAlias("性别", "sexCode");
            reader.addHeaderAlias("年级", "gradeName");
            reader.addHeaderAlias("所属院系", "collegeName");
            reader.addHeaderAlias("专业", "majorName");
            reader.addHeaderAlias("行政班名称", "className");
            reader.addHeaderAlias("上课校区", "campusName");

            excelTeachingActivities = reader.read(1, 2, ExcelStudentDto.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSiteExclusion(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {


        List<ExcelSiteExclusion> excelTeachingActivities = this.readSiteExclusion(file);


        if (flag == 2) {
            ruleTimeProhibitService.lambdaUpdate().eq(RuleTimeProhibit::getTaskId, taskId)
                    .eq(RuleTimeProhibit::getOptionType, 2).remove();
        }


        Map<String, Room> roomMap = roomService.lambdaQuery().eq(Room::getTaskId, taskId).list().stream()
                .collect(Collectors.toMap(Room::getRoomName, Function.identity(), (o1, o2) -> o1));


        Long index = 3L;
        for (ExcelSiteExclusion excelTeachingActivity : excelTeachingActivities) {
            excelTeachingActivity.setId(index);
            index++;
        }


        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
        for (ExcelSiteExclusion excelTeachingActivity : excelTeachingActivities) {
            if (StringUtils.isBlank(excelTeachingActivity.getRoomName())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                errorExcelVo.setErrorMsg(excelTeachingActivity.getId() + "行场地未设置");
                errorExcelVos.add(errorExcelVo);
            } else {
                if (ObjUtil.isNull(roomMap.get(excelTeachingActivity.getRoomName()))) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                    errorExcelVo.setErrorMsg(excelTeachingActivity.getRoomName() + "本学期场地不存在");
                    errorExcelVos.add(errorExcelVo);
                }
            }
        }


        Integer errorExcelVos1 = errorExcelVos.size();
        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入场地禁排信息错误",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入错误信息" + time + ".xls", response);
            throw new BizException("导入场地禁排信息错误");
        }

        if (errorExcelVos1 == 0) {
            List<ErrorExcelVo> errorExcelVos2 = new ArrayList<>();


            List<RuleTimeProhibit> ruleTimeProhibits = new ArrayList<>();

            for (ExcelSiteExclusion excelTeachingActivity : excelTeachingActivities) {

                List<@NotBlank String> timeCodes = ruleTimeProhibitService.lambdaQuery().eq(RuleTimeProhibit::getOptionId, 2)
                        .eq(RuleTimeProhibit::getOptionId, roomMap.get(excelTeachingActivity.getRoomName()).getRoomId()).
                        list().stream().map(RuleTimeProhibit::getTimeCode).collect(Collectors.toList());

                List<String> timeCode = new ArrayList<>(Arrays.asList(excelTeachingActivity.getTimeCode().split("、")));
                List<String> tc = new ArrayList<>();
                timeCode.forEach(o -> {
                    tc.add(convertToCode(o));
                    ;
                });

                tc.forEach(o -> {
                    if (!timeCodes.contains(o)) {
                        RuleTimeProhibit ruleTimeProhibit = new RuleTimeProhibit();
                        ruleTimeProhibit.setTaskId(taskId);
                        ruleTimeProhibit.setOptionType(2);
                        ruleTimeProhibit.setOptionId(roomMap.get(excelTeachingActivity.getRoomName()).getRoomId());

                        ruleTimeProhibit.setTimeCode(o);
                        ruleTimeProhibit.setFlag(1);

                        ruleTimeProhibit.setCollegeId("");
                        ruleTimeProhibits.add(ruleTimeProhibit);

                    }
                });


            }

            Integer errorExcelVos3 = errorExcelVos2.size();

            if (CollUtil.isNotEmpty(errorExcelVos2)) {
                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

                MyExcelUtils.exportExcel(errorExcelVos2,
                        "导入教学活动信息错误",
                        "错误信息",
                        ErrorExcelVo.class,
                        "导入错误信息" + time + ".xls", response);
                throw new BizException("导入教学活动信息错误");
            }

            if (errorExcelVos3 == 0) {

                if (CollUtil.isNotEmpty(ruleTimeProhibits)) {
                    ruleTimeProhibitService.saveOrUpdateBatch(ruleTimeProhibits);
                }
            }
        }


    }

    private String convertToCode(String o) {
        String day = o.substring(1, 2);
        String section = o.substring(o.indexOf("[") + 1, o.indexOf("节"));
        return "0" + day + "0" + section;
    }


    @Override
    public void exportAssignedPriorityOfTeachers(HttpServletResponse response, Integer taskId, String baseCollageId, String keyword, Integer dataRange, Integer currentPage, Integer pageSize) {
        PageInfo<TeacherWithRuleVo> teacherListWithRule = ruleTimeProhibitService.getTeacherListWithRule(taskId, baseCollageId, keyword, dataRange, 1, 100000);

        List<TeacherWithRuleVo> teacherListWithRuleList = teacherListWithRule.getList();


        List<ExcelAssignedPriorityOfTeachers> excelAssignedPriorityOfTeachers = new ArrayList<>();

        teacherListWithRuleList.forEach(o -> {
            ExcelAssignedPriorityOfTeachers excelAssignedPriorityOfTeachers1 = new ExcelAssignedPriorityOfTeachers();
            excelAssignedPriorityOfTeachers1.setTeacherName(o.getTeacherName());
            excelAssignedPriorityOfTeachers1.setTeacherNo(o.getBaseTeacherId());
            excelAssignedPriorityOfTeachers1.setCollegeName(o.getCollegeName());
            excelAssignedPriorityOfTeachers1.setCourseName(o.getCourseName());
            excelAssignedPriorityOfTeachers1.setTeacherType(o.getIdentity() == 1 ? "任课教师" : "助教教师");
            excelAssignedPriorityOfTeachers1.setFirstClass(o.getPriorityTimecode());
            excelAssignedPriorityOfTeachers1.setForbiddenClass(o.getForbbidenTimecode());
            excelAssignedPriorityOfTeachers.add(excelAssignedPriorityOfTeachers1);
        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}教师禁排优先排导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelAssignedPriorityOfTeachers,
                format,
                "教师禁排优先排导出",
                ExcelAssignedPriorityOfTeachers.class,
                "教师禁排优先排导出" + time + ".xls", response);


    }

    private List<ExcelSiteExclusion> readSiteExclusion(MultipartFile file) {

        List<ExcelSiteExclusion> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "教室名称", "校区", "所属楼宇", "所属楼层", "教室类型", "禁排课时");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("教室名称", "roomName");
            reader.addHeaderAlias("校区", "campusName");
            reader.addHeaderAlias("所属楼宇", "building");
            reader.addHeaderAlias("所属楼层", "floor");
            reader.addHeaderAlias("教室类型", "roomType");
            reader.addHeaderAlias("禁排课时", "timeCode");

            excelTeachingActivities = reader.read(1, 2, ExcelSiteExclusion.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;


    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void exportProhibitedFromDischarging(HttpServletResponse response, Integer taskId, Integer campusId, Integer buildingId, Integer floor, Integer roomType, String keyword, Integer dataRange, Integer currentPage, Integer pageSize) {


        List<ExcelProhibitedFromDischarging> excelProhibitedFromDischargings = new ArrayList<>();

        PageInfo<RoomWithRuleVo> roomListWithRule = ruleTimeProhibitService.getRoomListWithRule(taskId, campusId, buildingId, floor, roomType, keyword, null, dataRange, 1, 10000);

        List<RoomWithRuleVo> roomListWithRuleList = roomListWithRule.getList();

        roomListWithRuleList.forEach(o -> {

            ExcelProhibitedFromDischarging excelProhibitedFromDischarging = new ExcelProhibitedFromDischarging();

            excelProhibitedFromDischarging.setRoomName(o.getRoomName());

            excelProhibitedFromDischarging.setBuildingName(o.getBuildingName());

            excelProhibitedFromDischarging.setFloor(o.getBuildingFloor() + "层");

            excelProhibitedFromDischarging.setCampusName(o.getCampusName());

            excelProhibitedFromDischarging.setRoomType(o.getRoomTypeName());

            excelProhibitedFromDischarging.setProhibitTimeCode(o.getTimeCodes());

            excelProhibitedFromDischargings.add(excelProhibitedFromDischarging);
        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}场地禁排信息导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelProhibitedFromDischargings,
                format,
                "预选课日志导出",
                ExcelProhibitedFromDischarging.class,
                "预选课日志导出" + time + ".xls", response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importOfTheStartPlan(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {
        List<ExcelOfTheStartPlan> excelTeachingActivities = this.readOfTheStartPlan(file);

        if (flag == 2) {
            courseApplyService.lambdaUpdate().eq(CourseApply::getTaskId, taskId).remove();
        }

        List<Course> courseList = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list();

        //基础平台培养方案对应课程id
        List<String> baseCourseIds = planTeachingCourseService.lambdaQuery().eq(PlanTeachingCourse::getTaskId, taskId).list()
                .stream().map(PlanTeachingCourse::getBaseCourseId).distinct().collect(Collectors.toList());

        Map<String, List<Course>> courseMap = new HashMap<>();

        if (CollUtil.isNotEmpty(baseCourseIds)) {
            courseMap = courseList.stream().filter(p -> baseCourseIds.contains(p.getBaseCourseId())).collect(Collectors.groupingBy(Course::getCourseName));
        }


        Long index = 3L;
        for (ExcelOfTheStartPlan excelTeachingActivity : excelTeachingActivities) {
            excelTeachingActivity.setId(index);
            index++;
        }

        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
        for (ExcelOfTheStartPlan excelTeachingActivity : excelTeachingActivities) {
            if (StringUtils.isBlank(excelTeachingActivity.getCourseName())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                errorExcelVo.setErrorMsg(excelTeachingActivity.getId() + "行课程名称不存在");
                errorExcelVos.add(errorExcelVo);
            } else {
                List<Course> courses = courseMap.get(excelTeachingActivity.getCourseName());
                if (CollUtil.isEmpty(courses)) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                    errorExcelVo.setErrorMsg(excelTeachingActivity.getId() + "课程在培养方案未开启");
                    errorExcelVos.add(errorExcelVo);
                } else {
                    Course course = courseMap.get(excelTeachingActivity.getCourseName()).stream().filter(p -> p.getCourseCode().equals(excelTeachingActivity.getCourseCode())).findFirst().orElse(null);
                    if (ObjUtil.isNull(course)) {
                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                        errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                        errorExcelVo.setErrorMsg(excelTeachingActivity.getCourseName() + "课程在培养方案未开启");
                        errorExcelVos.add(errorExcelVo);
                    }
                }
            }

            if (ObjUtil.isNull(excelTeachingActivity.getLectureHour())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                errorExcelVo.setErrorMsg(excelTeachingActivity.getCourseName() + "对应学时为空");
                errorExcelVos.add(errorExcelVo);
            }
        }


        Integer errorExcelVos1 = errorExcelVos.size();
        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "开课计划导入信息错误",
                    "错误信息",
                    ErrorExcelVo.class,
                    "开课计划导入导入错误信息" + time + ".xls", response);
            throw new BizException("导入开课计划导入信息错误");
        }

        if (errorExcelVos1 == 0) {
            List<Long> courseIds = new ArrayList<>();
            List<CourseApply> courseApplies = new ArrayList<>();

            Map<String, List<ExcelOfTheStartPlan>> addCourseMap = excelTeachingActivities.stream().collect(Collectors.groupingBy(ExcelOfTheStartPlan::getCourseName));

            Map<String, List<Course>> finalCourseMap = courseMap;
            addCourseMap.forEach((key, value) -> {
                Map<String, List<ExcelOfTheStartPlan>> codeMap = value.stream().collect(Collectors.groupingBy(ExcelOfTheStartPlan::getCourseCode));
                codeMap.forEach((c, v) -> {
                    Course course = finalCourseMap.get(key).stream().filter(p -> p.getCourseCode().equals(c)).findFirst().orElse(null);
                    if (ObjUtil.isNotNull(course)) {
                        courseIds.add(course.getCourseId());
                        CourseApply courseApply = new CourseApply();
                        courseApply.setTaskId(taskId);
                        courseApply.setCourseId(course.getCourseId());
                        ExcelOfTheStartPlan excelOfTheStartPlan = v.stream().filter(p -> p.getHourType().equals(1)).findFirst().orElse(null);
                        if (ObjUtil.isNotNull(excelOfTheStartPlan)) {
                            courseApply.setLectureHour(excelOfTheStartPlan.getLectureHour());
                        } else {
                            courseApply.setLectureHour(0);
                        }

                        ExcelOfTheStartPlan excelOfTheStartPlan1 = v.stream().filter(p -> p.getHourType().equals(2)).findFirst().orElse(null);
                        if (ObjUtil.isNotNull(excelOfTheStartPlan1)) {
                            courseApply.setExperimentalHour(excelOfTheStartPlan1.getLectureHour());
                        } else {
                            courseApply.setExperimentalHour(0);
                        }

                        ExcelOfTheStartPlan excelOfTheStartPlan2 = v.stream().filter(p -> p.getHourType().equals(3)).findFirst().orElse(null);
                        if (ObjUtil.isNotNull(excelOfTheStartPlan2)) {
                            courseApply.setComputerHour(excelOfTheStartPlan2.getLectureHour());
                        } else {
                            courseApply.setComputerHour(0);
                        }


                        ExcelOfTheStartPlan excelOfTheStartPlan3 = v.stream().filter(p -> p.getHourType().equals(4)).findFirst().orElse(null);
                        if (ObjUtil.isNotNull(excelOfTheStartPlan3)) {
                            courseApply.setOtherHour(excelOfTheStartPlan3.getLectureHour());
                        } else {
                            courseApply.setOtherHour(0);
                        }

                        ExcelOfTheStartPlan excelOfTheStartPlan4 = v.get(0);
                        courseApply.setDescription(excelOfTheStartPlan4.getDescription());
                        courseApply.setOperationType(3);
                        courseApplies.add(courseApply);

                    }

                });

            });

//            if (CollUtil.isNotEmpty(courseApplies)) {
//                courseApplies.forEach(param -> {
//                    if (param.getComputerHour() != null && param.getComputerHour() != 0) {
//                        courseWeekService.lambdaUpdate()
//                                .eq(CourseWeek::getTaskId, taskId)
//                                .eq(CourseWeek::getHourType, 3)
//                                .eq(CourseWeek::getCourseId, param.getCourseId())
//                                .remove();
//                        CourseWeek week = new CourseWeek()
//                                .setHourType(3)
//                                .setHourTypeName("上机")
//                                .setCourseId(param.getCourseId())
//                                .setTaskId(taskId)
//                                .setTotalHour(param.getComputerHour())
//                                .setWeekNum(param.getWeekNum());
//                        courseWeekService.save(week);
//                    }
//                    if (param.getExperimentalHour() != null && param.getExperimentalHour() != 0) {
//                        courseWeekService.lambdaUpdate()
//                                .eq(CourseWeek::getTaskId, taskId)
//                                .eq(CourseWeek::getHourType, 2)
//                                .eq(CourseWeek::getCourseId, param.getCourseId())
//                                .remove();
//                        CourseWeek week = new CourseWeek()
//                                .setHourType(2)
//                                .setHourTypeName("实验")
//                                .setCourseId(param.getCourseId())
//                                .setTaskId(taskId)
//                                .setTotalHour(param.getComputerHour())
//                                .setWeekNum(param.getWeekNum());
//                        courseWeekService.save(week);
//                    }
//                    if (param.getLectureHour() != null && param.getLectureHour() != 0) {
//                        courseWeekService.lambdaUpdate()
//                                .eq(CourseWeek::getTaskId, taskId)
//                                .eq(CourseWeek::getHourType, 1)
//                                .eq(CourseWeek::getCourseId, param.getCourseId())
//                                .remove();
//                        CourseWeek week = new CourseWeek()
//                                .setHourType(1)
//                                .setHourTypeName("讲授")
//                                .setCourseId(param.getCourseId())
//                                .setTaskId(taskId)
//                                .setTotalHour(param.getComputerHour())
//                                .setWeekNum(param.getWeekNum());
//                        courseWeekService.save(week);
//                    }
//                    if (param.getOtherHour() != null && param.getOtherHour() != 0) {
//                        courseWeekService.lambdaUpdate()
//                                .eq(CourseWeek::getTaskId, taskId)
//                                .eq(CourseWeek::getHourType, 4)
//                                .eq(CourseWeek::getCourseId, param.getCourseId())
//                                .remove();
//                        CourseWeek week = new CourseWeek()
//                                .setHourType(4)
//                                .setHourTypeName("其他")
//                                .setCourseId(param.getCourseId())
//                                .setTaskId(taskId)
//                                .setTotalHour(param.getComputerHour())
//                                .setWeekNum(param.getWeekNum());
//                        courseWeekService.save(week);
//                    }
//
//                });
//
//            }


            if (CollUtil.isNotEmpty(courseIds)) {
                courseApplyService.lambdaUpdate().eq(CourseApply::getTaskId, taskId)
                        .in(CourseApply::getCourseId, courseIds).remove();
            }

            if (CollUtil.isNotEmpty(courseApplies)) {
                courseApplyService.saveOrUpdateBatch(courseApplies);
            }

        }


    }

    private List<ExcelOfTheStartPlan> readOfTheStartPlan(MultipartFile file) {

        List<ExcelOfTheStartPlan> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "课程名称", "课程代码", "授课类型", "授课学时", "状态说明");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("课程名称", "courseName");
            reader.addHeaderAlias("课程代码", "courseCode");
            reader.addHeaderAlias("授课类型", "hourType");
            reader.addHeaderAlias("授课学时", "lectureHour");
            reader.addHeaderAlias("状态说明", "description");

            excelTeachingActivities = reader.read(1, 2, ExcelOfTheStartPlan.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;
    }

    private List<ExcelStudentInformationSettings> readStudentInformationSettings(MultipartFile file) {


        List<ExcelStudentInformationSettings> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "所属院系", "专业", "年级", "上课校区");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("所属院系", "collegeName");
            reader.addHeaderAlias("专业", "majorName");
            reader.addHeaderAlias("年级", "gradeName");
            reader.addHeaderAlias("上课校区", "campusName");

            excelTeachingActivities = reader.read(1, 2, ExcelStudentInformationSettings.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;


    }

    private static void downLoadExcel(String fileName, HttpServletResponse response,
                                      Workbook workbook) {
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
            workbook.write(response.getOutputStream());

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importAssignedPriorityOfTeachers(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {

        List<ExcelAssignedPriorityOfTeachersVo> excelTeachingActivities = this.readAssignedPriorityOfTeachers(file);


        if (flag == 2) {
            ruleTimeProhibitService.lambdaUpdate().eq(RuleTimeProhibit::getTaskId, taskId)
                    .eq(RuleTimeProhibit::getOptionType, 4).remove();
        }


        List<RuleTimeProhibit> probitTiemcodes = ruleTimeProhibitService.lambdaQuery().eq(RuleTimeProhibit::getTaskId, taskId)
                .eq(RuleTimeProhibit::getOptionId, 4).list().stream().filter(p -> p.getFlag().equals(1))
                .filter(p -> StringUtils.isNotBlank(p.getTimeCode()))
                .collect(Collectors.toList());


        List<RuleTimeProhibit> priorityTimecode = ruleTimeProhibitService.lambdaQuery().eq(RuleTimeProhibit::getTaskId, taskId)
                .eq(RuleTimeProhibit::getOptionId, 4).list().stream().filter(p -> p.getFlag().equals(2))
                .filter(p -> StringUtils.isNotBlank(p.getTimeCode()))
                .collect(Collectors.toList());


        Map<String, Teacher> teacherMap = teacherService.lambdaQuery().eq(Teacher::getTaskId, taskId).list().stream()
                .collect(Collectors.toMap(Teacher::getBaseTeacherId, Function.identity(), (o1, o2) -> o1));


        Long index = 3L;
        for (ExcelAssignedPriorityOfTeachersVo excelTeachingActivity : excelTeachingActivities) {
            excelTeachingActivity.setId(index);
            index++;
        }


        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
        for (ExcelAssignedPriorityOfTeachersVo excelTeachingActivity : excelTeachingActivities) {
            if (StringUtils.isBlank(excelTeachingActivity.getTeacherNo()) || !teacherMap.containsKey(excelTeachingActivity.getTeacherNo())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                errorExcelVo.setErrorMsg(excelTeachingActivity.getTeacherName() + "教师不存在");
                errorExcelVos.add(errorExcelVo);
            }
            if (StringUtils.isBlank(excelTeachingActivity.getProhibitTimeCode()) && StringUtils.isBlank(excelTeachingActivity.getPriorityTimeCode())) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                errorExcelVo.setErrorMsg(excelTeachingActivity.getTeacherName() + "禁排课时和优先排课时均未设置");
                errorExcelVos.add(errorExcelVo);
            }


        }

        Integer errorExcelVos1 = errorExcelVos.size();
        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入教师禁排优先排信息错误",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入教师禁排优先排信息错误" + time + ".xls", response);
            throw new BizException("导入教师禁排优先排信息错误");
        }

        if (errorExcelVos1 == 0) {
            List<ErrorExcelVo> errorExcelVos2 = new ArrayList<>();


            List<RuleTimeProhibit> ruleTimeProhibits = new ArrayList<>();

            for (ExcelAssignedPriorityOfTeachersVo excelTeachingActivity : excelTeachingActivities) {

                Long teacherId = teacherMap.get(excelTeachingActivity.getTeacherNo()).getTeacherId();

                if (StringUtils.isNotBlank(excelTeachingActivity.getProhibitTimeCode())) {

                    List<String> timeCode = new ArrayList<>(Arrays.asList(excelTeachingActivity.getProhibitTimeCode().split("、")));

                    List<String> tc = new ArrayList<>();
                    timeCode.forEach(o -> {
                        tc.add(convertToCode(o));
                        ;
                    });


                    List<@NotBlank String> collect = probitTiemcodes.stream().filter(p -> p.getOptionId().equals(teacherId)).map(RuleTimeProhibit::getTimeCode).collect(Collectors.toList());

                    //禁排
                    tc.forEach(o -> {
                        if (!collect.contains(o)) {
                            RuleTimeProhibit ruleTimeProhibit = new RuleTimeProhibit();

                            ruleTimeProhibit.setTaskId(taskId);
                            ruleTimeProhibit.setOptionType(4);
                            ruleTimeProhibit.setOptionId(teacherId);
                            ruleTimeProhibit.setTimeCode(o);
                            ruleTimeProhibit.setFlag(1);

                            ruleTimeProhibit.setCollegeId("");
                            ruleTimeProhibits.add(ruleTimeProhibit);
                        }
                    });

                }


                if (StringUtils.isNotBlank(excelTeachingActivity.getPriorityTimeCode())) {

                    List<String> timeCode1 = new ArrayList<>(Arrays.asList(excelTeachingActivity.getPriorityTimeCode().split("、")));

                    List<String> tc = new ArrayList<>();
                    timeCode1.forEach(o -> {
                        tc.add(convertToCode(o));
                        ;
                    });

                    List<@NotBlank String> collect = priorityTimecode.stream().filter(p -> p.getOptionId().equals(teacherId)).map(RuleTimeProhibit::getTimeCode).collect(Collectors.toList());
                    //禁排
                    tc.forEach(o -> {
                        if (!collect.contains(o)) {
                            RuleTimeProhibit ruleTimeProhibit = new RuleTimeProhibit();

                            ruleTimeProhibit.setTaskId(taskId);
                            ruleTimeProhibit.setOptionType(4);
                            ruleTimeProhibit.setOptionId(teacherId);
                            ruleTimeProhibit.setTimeCode(o);
                            ruleTimeProhibit.setFlag(2);

                            ruleTimeProhibit.setCollegeId("");
                            ruleTimeProhibits.add(ruleTimeProhibit);
                        }
                    });
                }
            }

            Integer errorExcelVos3 = errorExcelVos2.size();

            if (CollUtil.isNotEmpty(errorExcelVos2)) {
                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

                MyExcelUtils.exportExcel(errorExcelVos2,
                        "导入教师禁排优先排信息错误",
                        "错误信息",
                        ErrorExcelVo.class,
                        "导入教师禁排优先排信息错误" + time + ".xls", response);
                throw new BizException("导入教师禁排优先排信息错误");
            }

            if (errorExcelVos3 == 0) {

                if (CollUtil.isNotEmpty(ruleTimeProhibits)) {
                    ruleTimeProhibitService.saveOrUpdateBatch(ruleTimeProhibits);
                }
            }
        }

    }


    @Override
    public void exportForbiddenOfCourse(HttpServletResponse response, Integer taskId, String baseCollageId, String keyword,
                                        String courseTypeId, Integer courseNature, Integer dataRange, Integer currentPage,
                                        Integer pageSize) {


        List<ExcelForbiddenOfCourse> excelForbiddenOfCourses = new ArrayList<>();

        PageInfo<TeachingClassWithRuleVo> teachingClassListWithRule = ruleTimeProhibitService.getTeachingClassListWithRule(taskId, baseCollageId, courseTypeId, courseNature,
                keyword, dataRange, 1, 1000000);

        List<TeachingClassWithRuleVo> list = teachingClassListWithRule.getList();

        list.forEach(o -> {

            ExcelForbiddenOfCourse excelForbiddenOfCourse = new ExcelForbiddenOfCourse();
            excelForbiddenOfCourse.setCourseName(o.getCourseName());
            excelForbiddenOfCourse.setCourseCode(o.getCourseCode());
            excelForbiddenOfCourse.setTeachingClassName(o.getTeachingClassName());
            List<TeacherDto> teachingClassTeachers = o.getTeachingClassTeachers();
            if (CollUtil.isNotEmpty(teachingClassTeachers)) {
                String teacherName = teachingClassTeachers.stream().filter(p -> p.getIdentity().equals(1)).map(TeacherDto::getTeacherName)
                        .collect(Collectors.joining(","));
                String teacherName1 = teachingClassTeachers.stream().filter(p -> p.getIdentity().equals(2)).map(TeacherDto::getTeacherName)
                        .collect(Collectors.joining(","));

                excelForbiddenOfCourse.setTeacherName(teacherName);
                excelForbiddenOfCourse.setIdentifyTeacherName(teacherName1);
            }
            excelForbiddenOfCourse.setCollegeName(o.getCollegeName());
            excelForbiddenOfCourse.setCourseType(o.getCourseType());
            excelForbiddenOfCourse.setCourseNature(o.getCourseNature() == 1 ? "必修" : "选修");
            excelForbiddenOfCourse.setCourseMethod(o.getHourType() == 1 ? "讲授" : o.getHourType() == 2 ? "实验" : o.getHourType() == 3 ? "上机" : "其他");
            excelForbiddenOfCourse.setForbiddenClass(o.getForbbidenTimecode());
            excelForbiddenOfCourse.setFirstClass(o.getPriorityTimecode());

            excelForbiddenOfCourses.add(excelForbiddenOfCourse);

        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}教师禁排优先排导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelForbiddenOfCourses,
                format,
                "课程禁排优先排导出",
                ExcelForbiddenOfCourse.class,
                "课程禁排优先排导出" + time + ".xls", response);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importForbiddenOfCourse(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {
//
//        List<ExcelForbiddenOfCourseVo> excelTeachingActivities = this.readForbiddenOfCourse(file);
//
//
//        if (flag == 2) {
//            ruleTimeProhibitService.lambdaUpdate().eq(RuleTimeProhibit::getTaskId, taskId)
//                    .eq(RuleTimeProhibit::getOptionType, 3).remove();
//        }
//
//
//        //禁排
//        List<RuleTimeProhibit> probitTiemcodes = ruleTimeProhibitService.lambdaQuery().eq(RuleTimeProhibit::getTaskId, taskId)
//                .eq(RuleTimeProhibit::getOptionId, 3).list().stream().filter(p -> p.getFlag().equals(1))
//                .filter(p -> StringUtils.isNotBlank(p.getTimeCode()))
//                .collect(Collectors.toList());
//
//
//        //优先排
//        List<RuleTimeProhibit> priorityTimecode = ruleTimeProhibitService.lambdaQuery().eq(RuleTimeProhibit::getTaskId, taskId)
//                .eq(RuleTimeProhibit::getOptionId, 3).list().stream().filter(p -> p.getFlag().equals(2))
//                .filter(p -> StringUtils.isNotBlank(p.getTimeCode()))
//                .collect(Collectors.toList());
//
//        Map<String, TeachingClass> teachingClassMap = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).list().stream()
//                .collect(Collectors.toMap(TeachingClass::getTeachingClassName, Function.identity(), (o1, o2) -> o1));
//
//
//        Long index = 3L;
//        for (ExcelForbiddenOfCourseVo excelTeachingActivity : excelTeachingActivities) {
//            excelTeachingActivity.setId(index);
//            index++;
//        }
//
//
//        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
//        for (ExcelForbiddenOfCourseVo excelTeachingActivity : excelTeachingActivities) {
//            if (StringUtils.isBlank(excelTeachingActivity.getTeachingClassName()) || !teachingClassMap.containsKey(excelTeachingActivity.getTeachingClassName())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getTeachingClassName() + "该教学班不存在");
//                errorExcelVos.add(errorExcelVo);
//            }
//            if (StringUtils.isBlank(excelTeachingActivity.getForbiddenClass()) && StringUtils.isBlank(excelTeachingActivity.getFirstClass())) {
//                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
//                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
//                errorExcelVo.setErrorMsg(excelTeachingActivity.getTeachingClassName() + "禁排课时和优先排课时均未设置");
//                errorExcelVos.add(errorExcelVo);
//            }
//
//        }
//
//        Integer errorExcelVos1 = errorExcelVos.size();
//        if (CollUtil.isNotEmpty(errorExcelVos)) {
//            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
//            response.setCharacterEncoding("UTF-8");
//            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
//
//            MyExcelUtils.exportExcel(errorExcelVos,
//                    "导入场地禁排信息错误",
//                    "错误信息",
//                    ErrorExcelVo.class,
//                    "导入错误信息" + time + ".xls", response);
//            throw new BizException("导入场地禁排信息错误");
//        }
//
//        if (errorExcelVos1 == 0) {
//            List<ErrorExcelVo> errorExcelVos2 = new ArrayList<>();
//
//            List<RuleTimeProhibit> ruleTimeProhibits = new ArrayList<>();
//
//            for (ExcelForbiddenOfCourseVo excelTeachingActivity : excelTeachingActivities) {
//
//                Long teachingClassId = teachingClassMap.get(excelTeachingActivity.getTeachingClassName()).getTeachingClassId();
//
//                if (StringUtils.isNotBlank(excelTeachingActivity.getForbiddenClass())) {
//
//                    List<String> timeCode = new ArrayList<>(Arrays.asList(excelTeachingActivity.getForbiddenClass().split("、")));
//
//                    List<String> tc = new ArrayList<>();
//                    timeCode.forEach(o -> {
//                        tc.add(convertToCode(o));
//                        ;
//                    });
//
//
//                    List<@NotBlank String> collect = probitTiemcodes.stream().filter(p -> p.getOptionId().equals(teachingClassId)).map(RuleTimeProhibit::getTimeCode).collect(Collectors.toList());
//
//                    //禁排
//
//                    tc.forEach(o -> {
//                        if (!collect.contains(o)) {
//                            RuleTimeProhibit ruleTimeProhibit = new RuleTimeProhibit();
//
//                            ruleTimeProhibit.setTaskId(taskId);
//                            ruleTimeProhibit.setOptionType(3);
//                            ruleTimeProhibit.setOptionId(teachingClassId);
//                            ruleTimeProhibit.setTimeCode(o);
//                            ruleTimeProhibit.setFlag(1);
//                            ruleTimeProhibit.setHourType("讲授".equals(excelTeachingActivity.getHourType()) ? 1 : ("实验".equals(excelTeachingActivity.getHourType())) ? 2 : ("上机".equals(excelTeachingActivity.getHourType()) ? 3 : ("其他".equals(excelTeachingActivity.getHourType()) ? 4 : 0)));
//
//                            ruleTimeProhibit.setCollegeId("");
//                            ruleTimeProhibits.add(ruleTimeProhibit);
//                        }
//                    });
//
//                }
//
//
//                if (StringUtils.isNotBlank(excelTeachingActivity.getFirstClass())) {
//
//                    List<String> timeCode1 = new ArrayList<>(Arrays.asList(excelTeachingActivity.getFirstClass().split("、")));
//
//                    List<String> tc = new ArrayList<>();
//                    timeCode1.forEach(o -> {
//                        tc.add(convertToCode(o));
//                        ;
//                    });
//
//                    List<@NotBlank String> collect = priorityTimecode.stream().filter(p -> p.getOptionId().equals(teachingClassId)).map(RuleTimeProhibit::getTimeCode).collect(Collectors.toList());
//                    //禁排
//                    tc.forEach(o -> {
//                        if (!collect.contains(o)) {
//                            RuleTimeProhibit ruleTimeProhibit = new RuleTimeProhibit();
//
//                            ruleTimeProhibit.setTaskId(taskId);
//                            ruleTimeProhibit.setOptionType(3);
//                            ruleTimeProhibit.setOptionId(teachingClassId);
//                            ruleTimeProhibit.setTimeCode(o);
//                            ruleTimeProhibit.setFlag(2);
//
//                            ruleTimeProhibit.setCollegeId("");
//                            ruleTimeProhibit.setHourType("讲授".equals(excelTeachingActivity.getHourType()) ? 1 : ("实验".equals(excelTeachingActivity.getHourType())) ? 2 : ("上机".equals(excelTeachingActivity.getHourType()) ? 3 : ("其他".equals(excelTeachingActivity.getHourType()) ? 4 : 0)));
//                            ruleTimeProhibits.add(ruleTimeProhibit);
//                        }
//                    });
//
//                }
//
//            }
//
//            Integer errorExcelVos3 = errorExcelVos2.size();
//
//            if (CollUtil.isNotEmpty(errorExcelVos2)) {
//                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
//                response.setCharacterEncoding("UTF-8");
//                response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
//
//                MyExcelUtils.exportExcel(errorExcelVos2,
//                        "导入教学活动信息错误",
//                        "错误信息",
//                        ErrorExcelVo.class,
//                        "导入错误信息" + time + ".xls", response);
//                throw new BizException("导入教学活动信息错误");
//            }
//
//            if (errorExcelVos3 == 0) {
//
//                if (CollUtil.isNotEmpty(ruleTimeProhibits)) {
//                    ruleTimeProhibitService.saveOrUpdateBatch(ruleTimeProhibits);
//                }
//            }
//        }

    }


    @Override
    public void exportSetCourseSelection(HttpServletResponse response, Integer taskId, Optional<Integer> type) {
        List<ExcelPreSelect> excelPreSelects = new ArrayList<>();
        List<RoundListDto> roundList = selectCourseService.getRoundList(type, taskId);


        roundList.forEach(o -> {
            ExcelPreSelect excelPreSelect = new ExcelPreSelect();

            excelPreSelect.setSelectRound(o.getRoundName());

            excelPreSelect.setCourseSelectionAuthority(o.getSelectAuthority() == 1 ? "可退/可选" : (o.getSelectAuthority() == 2 ? "仅可选" : "仅可退"));

            excelPreSelect.setStartTime(o.getBeginTime());

            excelPreSelect.setEndTime(o.getEndTime());

            excelPreSelect.setSelectNum(o.getStudentNum());

            List<CssStudentRange> studentRange = o.getStudentRange();

            Map<String, List<CssStudentRange>> collegeMap = studentRange.stream().collect(Collectors.groupingBy(CssStudentRange::getBaseCollegeId));

            List<ExcelCollegeSelectDto> excelCollegeSelectDtos = new ArrayList<>();
            collegeMap.forEach((key, value) -> {
                CssStudentRange cssStudentRange = value.get(0);
                ExcelCollegeSelectDto excelCollegeSelectDto = new ExcelCollegeSelectDto();
                excelCollegeSelectDto.setSelectCollege(cssStudentRange.getCollegeName());
                String gradeName = value.stream().map(CssStudentRange::getGradeName).distinct().collect(Collectors.joining(","));
                excelCollegeSelectDto.setSelectGradeName(gradeName);
                excelCollegeSelectDtos.add(excelCollegeSelectDto);
            });

            excelPreSelect.setCollegeSelectDtos(excelCollegeSelectDtos);

            excelPreSelect.setSelectNum(o.getTotalStudent());


            excelPreSelect.setSelectState(o.getIsEnable() == 0 ? "未开始" : "选课中");

            excelPreSelects.add(excelPreSelect);

        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}选课信息导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelPreSelects,
                format,
                "选课轮次",
                ExcelPreSelect.class,
                "设置选课轮次导出" + time + ".xls", response);
    }


    @Override
    public void exportOfStudent(HttpServletResponse response, Integer taskId, String courseName, String collegeName, String courseName1, String courseType, String courseNatureName, String selectStudentNums, String state, String isCourseState,
                                String baseCollegeId, String courseTypeId, Optional<Integer> courseNature, String keyword, Optional<Integer> isEnable, Optional<Integer> isAchieveOpen, Integer pageSize, Integer currentPage) {
        //构造列名
        List<ExcelExportEntity> entityList = new ArrayList<>();


        if (ObjUtil.isNotNull(courseName)) {
            ExcelExportEntity entity = new ExcelExportEntity("课程", "courseName");
            entityList.add(entity);
        }

        if (StringUtils.isNotBlank(collegeName)) {
            ExcelExportEntity entity = new ExcelExportEntity("开课单位", "collegeName");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(courseType)) {
            ExcelExportEntity entity = new ExcelExportEntity("课程类别", "courseType");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(courseNatureName)) {
            ExcelExportEntity entity = new ExcelExportEntity("课程性质", "courseNature");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(selectStudentNums)) {
            ExcelExportEntity entity = new ExcelExportEntity("已选人数", "selectStudentNums");
            entityList.add(entity);
        }


        if (StringUtils.isNotBlank(state)) {
            ExcelExportEntity entity = new ExcelExportEntity("说明", "state");
            entityList.add(entity);
        }

        if (StringUtils.isNotBlank(isCourseState)) {
            ExcelExportEntity entity = new ExcelExportEntity("开课状态", "isCourseState");
            entityList.add(entity);
        }

        ExportParams params = new ExportParams();

        ResultDto<PreResultDto> preResultList = selectCourseService.getPreResultList(baseCollegeId, courseTypeId, courseNature, keyword, isEnable, isAchieveOpen, -1, 1, taskId);
        List<Map<String, Object>> resultList = new ArrayList<>();
        preResultList.getList().forEach(o -> {
            Map<String, Object> rowMap = new HashMap<>();
            rowMap.put("courseName", o.getCourseName());
            rowMap.put("collegeName", o.getCollegeName());
            rowMap.put("courseType", o.getCourseType());
            rowMap.put("courseNature", o.getCourseNature());
            rowMap.put("selectStudentNums", o.getStudentNum());
            rowMap.put("isCourseState", o.getIsEnable() == 0 ? "取消开班" : "正常开班");
            rowMap.put("state", o.getDescription());
            resultList.add(rowMap);
        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {}预选课结果导出 {}学期";
        String format = StrUtil.format(title, taskInfo.getSchoolName(), taskInfo.getTerm());

        //生成要导出的数据
        Workbook workbook = ExcelExportUtil.exportExcel(params, entityList, resultList);

        if (workbook != null) {
            downLoadExcel(format, response, workbook);
        }
    }


    @Override
    public void exportSelectLog(HttpServletResponse response, Integer taskId, Long roundId, String baseCollegeId, String gradeId, String classId, Integer courseId, String startDateTime, String endDateTime, String keyword, Integer pageSize, Integer currentPage) {

        List<ExcelPreSelectCourseLog> excelPreSelectCourseLogs = new ArrayList<>();

        Optional<Integer> id = Optional.ofNullable(courseId);
        ResultDto<CssLogsDto> cssLogs = selectCourseService.getCssLogs(roundId, baseCollegeId, gradeId, classId, id, startDateTime, endDateTime, keyword, 10000, 1, taskId);


        Map<Long, Course> courseMap = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list().stream().collect(Collectors.toMap(Course::getCourseId, Function.identity()));

        cssLogs.getList().forEach(o -> {
            ExcelPreSelectCourseLog excelPreSelectCourseLog = new ExcelPreSelectCourseLog();
            excelPreSelectCourseLog.setStudentName(o.getStudentName() + "(" + o.getBaseStudentId() + ")");
            excelPreSelectCourseLog.setCollegeName(o.getCollegeName());
            excelPreSelectCourseLog.setGradeName(o.getGradeName());

            excelPreSelectCourseLog.setClassName(o.getClassName());

            excelPreSelectCourseLog.setOption(o.getFlag() == 1 ? "选课" : (o.getFlag() == 2 ? "退选" : "管理员移除"));

            excelPreSelectCourseLog.setCourseName(ObjUtil.isNotNull(courseMap.get(o.getCourseId())) ? courseMap.get(o.getCourseId()).getCourseName()
                    + "(" + courseMap.get(o.getCourseId()).getBaseCourseId() + ")" : o.getCourseName());

            excelPreSelectCourseLog.setSelectTime(o.getModifiedTime());

            excelPreSelectCourseLogs.add(excelPreSelectCourseLog);

        });

        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}预选课信息日志导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelPreSelectCourseLogs,
                format,
                "选课日志导出",
                ExcelPreSelectCourseLog.class,
                "选课日志导出" + time + ".xls", response);
    }

    private List<ExcelCourseRule> readForbiddenOfCourse(MultipartFile file) {
        List<ExcelCourseRule> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "课程名称", "课程编号", "开课单位", "课程类别", "课程性质", "单日授课最大节数");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("课程名称", "courseName");
            reader.addHeaderAlias("课程编号", "courseCode");
            reader.addHeaderAlias("开课单位", "collegeName");
            reader.addHeaderAlias("课程类别", "courseType");
            reader.addHeaderAlias("课程性质", "courseNature");
            reader.addHeaderAlias("单日授课最大节数", "courseLimit");
            excelTeachingActivities = reader.read(1, 2, ExcelCourseRule.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;

    }

    private List<ExcelAssignedPriorityOfTeachersVo> readAssignedPriorityOfTeachers(MultipartFile file) {

        List<ExcelAssignedPriorityOfTeachersVo> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "教师名称", "教师工号", "所属院系", "授课课程", "教师类别", "禁排课时", "优先排课时");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("教师名称", "teacherName");
            reader.addHeaderAlias("教师工号", "teacherNo");
            reader.addHeaderAlias("所属院系", "collegeName");
            reader.addHeaderAlias("授课课程", "courseName");
            reader.addHeaderAlias("教师类别", "teacherType");
            reader.addHeaderAlias("禁排课时", "prohibitTimeCode");
            reader.addHeaderAlias("优先排课时", "priorityTimeCode");

            excelTeachingActivities = reader.read(1, 2, ExcelAssignedPriorityOfTeachersVo.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportOfClass(HttpServletResponse response, String collegeName, String majorName, String gradeName, String campusName, String teacherName, Integer taskId, Integer flag, Integer campusId, String baseCollegeId, String gradeId, String baseMajorId, String keyword, Long teacherId) {

        if (schoolFlag.equals(1)) {
            Map<String, List<ColEntity>> heads = new HashMap<>();// 最终导出的多个sheet的表头
            Map<String, List<Map<String, String>>> datas = new HashMap<>();// 最终导出的多个sheet的内容
            Map<String, Integer> types = new HashMap<>();// 最终导出的每个sheet的样式类型
            Map<String, List<Integer>> mergeIndexs = new HashMap<>();
            multilevelHeaderMap(heads, datas, types, taskId, flag, campusId, baseCollegeId, gradeId, baseMajorId, keyword, teacherId);

            ExcelPoiUtil excelTool = new ExcelPoiUtil("教学班数据导出");
            HSSFWorkbook workbook = null;
            try {
                workbook = excelTool.exportWorkbook(heads, datas, types, null, mergeIndexs);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (null != response) {
                // 下边两行任取一行都可以
                response.addHeader("Content-Type", "application/vnd.ms-excel;charset=UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=\"data.xls\"");
            }
            try {
                OutputStream out = response.getOutputStream();
                workbook.write(out);
                out.flush();
                out.close();
            } catch (IOException e) {
                log.error("行政班导出错误" + e);
            }

        } else {

            List<ExcelTeachingClass> excelTeachingClasses = new ArrayList<>();

            TaskInfo taskInfo = taskInfoService.getById(taskId);

            //获取总周次
            ResultDto<TeachingClass> teachingClassHourList = teachingClassService.getTeachingClassHourList(1, 100000, taskId, flag, campusId, baseCollegeId, gradeId, baseMajorId, keyword, teacherId);


            List<TeachingClass> list = teachingClassHourList.getList();

            list.forEach(o -> {
                ExcelTeachingClass excelTeachingClass = new ExcelTeachingClass();

                excelTeachingClass.setTeachingClassName(o.getTeachingClassName());
                excelTeachingClass.setCourseName(o.getCourseName());
                excelTeachingClass.setCollegeName(o.getCollegeName());
                excelTeachingClass.setCampusName(o.getCampusName());
                excelTeachingClass.setFlag(o.getFlag().equals(1) ? "课程" : "环节");
                excelTeachingClass.setStudentNum(o.getClassNum());
                excelTeachingClass.setAssessmentMethod(o.getAssessmentName());

                List<TeachingClassWeekExcelVo> teachingClassWeekExcelVos = new ArrayList<>();
                List<TeachingClassWeek> teachingClassWeeks = o.getTeachingClassWeeks();
                if (!CollUtil.isEmpty(teachingClassWeeks)) {
                    teachingClassWeeks.forEach(tw -> {
                        TeachingClassWeekExcelVo teachingClassWeekExcelVo = new TeachingClassWeekExcelVo();
                        teachingClassWeekExcelVo.setHourType(tw.getHourTypeName());
                        teachingClassWeekExcelVo.setRoomType(tw.getRoomTypeName());
                        teachingClassWeekExcelVo.setRoom(tw.getRoomName());
                        int count = 0;
                        if (StringUtils.isNotBlank(tw.getWeek())) {
                            char[] chars = tw.getWeek().toCharArray();
                            StringBuilder sb = new StringBuilder();
                            for (int i = 0; i < chars.length; i++) {
                                if (chars[i] == '1') {
                                    sb.append((i + 1) + ",");
                                    count++;
                                }
                            }
                            String s = sb.toString();
                            s = s.substring(0, s.length() - 1) + "周";

                            teachingClassWeekExcelVo.setWeek(s);
                        }
                        teachingClassWeekExcelVo.setTotalHour(tw.getWeekNum() * count);
                        teachingClassWeekExcelVo.setWeekNum(tw.getWeekNum());
                        teachingClassWeekExcelVo.setConnectSection(tw.getConnectSection());
                        teachingClassWeekExcelVo.setConnectNumber(tw.getConnectNumber());
                        List<TeachingClassTeacher> teachers = o.getTeachingClassTeachers().stream().filter(p -> p.getHourType().equals(tw.getHourType()) && tw.getTeachingClassId().equals(p.getTeachingClassId())).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(teachers)) {
                            List<TeachingClassTeacher> teacherList = teachers.stream().filter(p -> p.getIdentity().equals(1)).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(teacherList)) {
                                String teacherNames = teacherList.stream().map(TeachingClassTeacher::getTeacherName).collect(Collectors.joining(","));
                                teachingClassWeekExcelVo.setTeacherNo(teacherNames);
                            }


                            List<TeachingClassTeacher> teacherList1 = teachers.stream().filter(p -> p.getIdentity().equals(2)).collect(Collectors.toList());
                            if (CollUtil.isNotEmpty(teacherList1)) {
                                String teacherNames = teacherList1.stream().map(TeachingClassTeacher::getTeacherName).collect(Collectors.joining(","));
                                teachingClassWeekExcelVo.setAssTeacherNo(teacherNames);
                            }
                        }

                        teachingClassWeekExcelVos.add(teachingClassWeekExcelVo);

                    });
                    excelTeachingClass.setTeachingClassWeekExcelVoList(teachingClassWeekExcelVos);
                }
                excelTeachingClasses.add(excelTeachingClass);

            });


            //构建标题
            String title = " {} {}确认教学任务按教学班导出" + "\n" + "院系:{}" + "\n" + "年级:{}" + "\n" + "专业:{}" + "\n" + "校区:{}";
            String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                    , StringUtils.isNotBlank(collegeName) ? collegeName : "全部院系"
                    , StringUtils.isNotBlank(gradeName) ? gradeName : "全部年级"
                    , StringUtils.isNotBlank(majorName) ? majorName : "全部专业",
                    StringUtils.isNotBlank(campusName) ? campusName : "全部校区");


            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(excelTeachingClasses,
                    format,
                    "按教学班",
                    ExcelTeachingClass.class,
                    "确认教学任务按教学班导出" + time + ".xls", response);


        }


    }

    private void multilevelHeaderMap(Map<String, List<ColEntity>> heads, Map<String, List<Map<String, String>>> datas,
                                     Map<String, Integer> types, Integer taskId, Integer flag, Integer campusId,
                                     String baseCollegeId, String gradeId, String baseMajorId, String keyword, Long teacherId) {

        List<Map<String, String>> titleList = new ArrayList<>();
        Map<String, String> titleMap15 = new HashMap<>();
        titleMap15.put("id", "15");
        titleMap15.put("pid", "0");
        titleMap15.put("content", "班级数");
        titleMap15.put("fieldName", "collage");
        titleMap15.put("width", "20");
        Map<String, String> titleMap16 = new HashMap<>();
        titleMap16.put("id", "16");
        titleMap16.put("pid", "0");
        titleMap16.put("content", "学分");
        titleMap16.put("fieldName", "collage");
        titleMap16.put("width", "20");
        Map<String, String> titleMap17 = new HashMap<>();
        titleMap17.put("id", "17");
        titleMap17.put("pid", "0");
        titleMap17.put("content", "任课教师");
        titleMap17.put("fieldName", "teachers");
        titleMap17.put("width", "20");
        Map<String, String> titleMap18 = new HashMap<>();
        titleMap18.put("id", "18");
        titleMap18.put("pid", "0");
        titleMap18.put("content", "合班情况");
        titleMap18.put("fieldName", "mixClass");
        titleMap18.put("width", "20");
        Map<String, String> titleMap19 = new HashMap<>();
        titleMap19.put("id", "19");
        titleMap19.put("pid", "0");
        titleMap19.put("content", "上课起止周次");
        titleMap19.put("fieldName", "week");
        titleMap19.put("width", "20");


        Map<String, String> titleMap20 = new HashMap<>();
        titleMap20.put("id", "20");
        titleMap20.put("pid", "0");
        titleMap20.put("content", "实际排课总学时");
        titleMap20.put("fieldName", "totalHour");
        titleMap20.put("width", "20");


        Map<String, String> titleMap21 = new HashMap<>();
        titleMap21.put("id", "21");
        titleMap21.put("pid", "0");
        titleMap21.put("content", "备注");
        titleMap21.put("fieldName", "reserve");
        titleMap21.put("width", "20");


        Map<String, String> titleMap23 = new HashMap<>();
        titleMap23.put("id", "23");
        titleMap23.put("pid", "0");
        titleMap23.put("content", "班级数");
        titleMap23.put("fieldName", "classNum");
        titleMap23.put("width", "20");


        Map<String, String> titleMap22 = new HashMap<>();
        titleMap22.put("id", "22");
        titleMap22.put("pid", "0");
        titleMap22.put("content", "学分");
        titleMap22.put("fieldName", "credit");
        titleMap22.put("width", "20");


        Map<String, String> titleMap10 = new HashMap<>();
        titleMap10.put("id", "10");
        titleMap10.put("pid", "0");
        titleMap10.put("content", "序号");
        titleMap10.put("fieldName", "number");
        titleMap10.put("width", "20");
        Map<String, String> titleMap11 = new HashMap<>();
        titleMap11.put("id", "111");
        titleMap11.put("pid", "0");
        titleMap11.put("content", "二级学院");
        titleMap11.put("fieldName", "collage");
        titleMap11.put("width", "20");
        Map<String, String> titleMap12 = new HashMap<>();
        titleMap12.put("id", "12");
        titleMap12.put("pid", "0");
        titleMap12.put("content", "专业");
        titleMap12.put("fieldName", "major");
        titleMap12.put("width", "20");
        Map<String, String> titleMap13 = new HashMap<>();
        titleMap13.put("id", "13");
        titleMap13.put("pid", "0");
        titleMap13.put("content", "班级");
        titleMap13.put("fieldName", "class");
        titleMap13.put("width", "20");
        Map<String, String> titleMap14 = new HashMap<>();
        titleMap14.put("id", "14");
        titleMap14.put("pid", "0");
        titleMap14.put("content", "学生人数");
        titleMap14.put("fieldName", "studentNum");
        titleMap14.put("width", "20");
        Map<String, String> titleMap = new HashMap<>();
        titleMap.put("id", "11");
        titleMap.put("pid", "0");
        titleMap.put("content", "课程代码");
        titleMap.put("fieldName", "courseCode");
        titleMap.put("width", "20");
        Map<String, String> titleMap1 = new HashMap<>();
        titleMap1.put("id", "1");
        titleMap1.put("pid", "0");
        titleMap1.put("content", "课程名称");
        titleMap1.put("fieldName", "courseName");
        titleMap1.put("width", "20");
        Map<String, String> titleMap2 = new HashMap<>();
        titleMap2.put("id", "2");
        titleMap2.put("pid", "0");
        titleMap2.put("content", "计划课时");
        titleMap2.put("fieldName", null);
        titleMap2.put("width", "20");
        Map<String, String> titleMap8 = new HashMap<>();
        titleMap8.put("id", "5");
        titleMap8.put("pid", "2");
        titleMap8.put("content", "考核类型");
        titleMap8.put("fieldName", null);
        titleMap8.put("width", "20");
        Map<String, String> titleMap24 = new HashMap<>();
        titleMap24.put("id", "24");
        titleMap24.put("pid", "5");
        titleMap24.put("content", "考核方式");
        titleMap24.put("fieldName", "assessment");
        titleMap24.put("width", "20");
        Map<String, String> titleMap9 = new HashMap<>();
        titleMap9.put("id", "6");
        titleMap9.put("pid", "2");
        titleMap9.put("content", "周学时");
        titleMap9.put("fieldName", "weekNum");
        titleMap9.put("width", "20");
        Map<String, String> titleMap25 = new HashMap<>();
        titleMap25.put("id", "25");
        titleMap25.put("pid", "2");
        titleMap25.put("content", "理论实践分组");
        titleMap25.put("fieldName", null);
        titleMap25.put("width", "20");
        Map<String, String> titleMap26 = new HashMap<>();
        titleMap26.put("id", "26");
        titleMap26.put("pid", "25");
        titleMap26.put("content", "理论分组");
        titleMap26.put("fieldName", "11");
        titleMap26.put("width", "20");
        Map<String, String> titleMap27 = new HashMap<>();
        titleMap27.put("id", "27");
        titleMap27.put("pid", "25");
        titleMap27.put("content", "实践分组");
        titleMap27.put("fieldName", "22");
        titleMap27.put("width", "20");
        Map<String, String> titleMap3 = new HashMap<>();
        titleMap3.put("id", "3");
        titleMap3.put("pid", "2");
        titleMap3.put("content", "总课时");
        titleMap3.put("fieldName", "totalNum");
        titleMap3.put("width", "15");
        Map<String, String> titleMap4 = new HashMap<>();
        titleMap4.put("id", "4");
        titleMap4.put("pid", "2");
        titleMap4.put("content", "总课时");
        titleMap4.put("fieldName", null);
        titleMap4.put("width", "15");
        Map<String, String> titleMap5 = new HashMap<>();
        titleMap5.put("id", "22");
        titleMap5.put("pid", "4");
        titleMap5.put("content", "理");
        titleMap5.put("fieldName", "lecture");
        titleMap5.put("width", "20");
        Map<String, String> titleMap6 = new HashMap<>();
        titleMap6.put("id", "22_1");
        titleMap6.put("pid", "4");
        titleMap6.put("content", "实");
        titleMap6.put("fieldName", "experiment");
        titleMap6.put("width", "10");
        Map<String, String> titleMap7 = new HashMap<>();
        titleMap7.put("id", "22_2");
        titleMap7.put("pid", "4");
        titleMap7.put("content", "课外");
        titleMap7.put("fieldName", "other");
        titleMap7.put("width", "10");

        titleList.add(titleMap10);
        titleList.add(titleMap11);
        titleList.add(titleMap12);
        titleList.add(titleMap13);
        titleList.add(titleMap14);
        titleList.add(titleMap);
        titleList.add(titleMap1);
        titleList.add(titleMap23);
        titleList.add(titleMap22);
        titleList.add(titleMap2);
        titleList.add(titleMap3);
        titleList.add(titleMap4);
        titleList.add(titleMap5);
        titleList.add(titleMap6);
        titleList.add(titleMap7);
        titleList.add(titleMap8);
        titleList.add(titleMap24);
        titleList.add(titleMap9);
        titleList.add(titleMap25);
        titleList.add(titleMap26);
        titleList.add(titleMap27);
        titleList.add(titleMap17);
        titleList.add(titleMap18);
        titleList.add(titleMap19);
        titleList.add(titleMap20);
        titleList.add(titleMap21);
        // 单级的 行内数据
        List<Map<String, String>> rowList = new ArrayList<>();

        //获取总周次
        ResultDto<TeachingClass> teachingClassHourList = teachingClassService.getTeachingClassHourList(1, 100000,
                taskId, flag, campusId, baseCollegeId, gradeId, baseMajorId, keyword, teacherId);

        List<TeachingClass> list = teachingClassHourList.getList();

        List<Long> teachingClassIds = list.stream().map(TeachingClass::getTeachingClassId).distinct().collect(Collectors.toList());

        List<TeachingClassStudent> teachingClassStudents = new ArrayList<>();
        List<Course> courses = new ArrayList<>();
        List<Student> students = new ArrayList<>();
        List<Teacher> teacherList = new ArrayList<>();
        if (CollUtil.isNotEmpty(list)) {
            students = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();
            teachingClassStudents = teachingClassStudentService.lambdaQuery().in(TeachingClassStudent::getTeachingClassId, teachingClassIds).list();
            courses = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list();
            teacherList = teacherService.lambdaQuery().eq(Teacher::getTaskId, taskId).list();
        }

        int num = 1;
        for (TeachingClass teachingClass : list) {
            Map<String, String> m = new HashMap<>();
            m.put("number", String.valueOf(num++));
            m.put("collage", teachingClass.getCollegeName());
            List<TeachingClassStudent> teachingClassStudentList = teachingClassStudents.stream().filter(p -> p.getTeachingClassId().equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(teachingClassStudentList)) {
                List<Long> ids = teachingClassStudentList.stream().map(TeachingClassStudent::getStudentId).collect(Collectors.toList());
                List<Student> studentList = students.stream().filter(p -> ids.contains(p.getStudentId())).collect(Collectors.toList());
                if (CollUtil.isNotEmpty(studentList)) {
                    String majorName = studentList.stream().map(Student::getMajorName).distinct().collect(Collectors.joining("、"));
                    m.put("major", majorName);
                    String className = studentList.stream().map(Student::getClassName).distinct().collect(Collectors.joining("、"));
                    m.put("class", className);
                    long count = studentList.stream().map(Student::getClassName).distinct().count();
                    m.put("classNum", String.valueOf(count));
                    m.put("studentNum", String.valueOf(studentList.size()));
                } else {
                    m.put("studentNum", String.valueOf(0));
                }
            }

            Course course = courses.stream().filter(p -> p.getCourseId().equals(teachingClass.getCourseId())).findFirst().orElse(null);
            if (ObjUtil.isNotNull(course)) {
                m.put("courseCode", course.getCourseCode());
                m.put("courseName", course.getCourseName());
                m.put("credit", String.valueOf(course.getCredit()));
            }

            if (teachingClass.getFlag().equals(1)) {
                List<TeachingClassWeek> teachingClassWeekList = teachingClass.getTeachingClassWeeks();
                if (CollUtil.isNotEmpty(teachingClassWeekList)) {
                    int sum = teachingClassWeekList.stream().map(TeachingClassWeek::getTotalHour).mapToInt(Integer::intValue).sum();
//                    int sum1 = teachingClassWeekList.stream().map(TeachingClassWeek::getNeedScheduleHour).mapToInt(Integer::intValue).sum();

                    AtomicInteger suml = new AtomicInteger();

                    teachingClassWeekList.forEach(o -> {
                        int weekSize = WeekUtil.weekSize(o.getWeek());

                        int weekNum = weekSize * o.getWeekNum();

                        suml.addAndGet(weekNum);

                    });


                    m.put("totalNum", String.valueOf(sum));
                    m.put("totalHour", String.valueOf(suml.get()));
                    List<TeachingClassWeek> teachingClassWeek = teachingClassWeekList.stream().filter(p -> p.getHourType().equals(1)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teachingClassWeek)) {
                        int count = 0;
                        for (TeachingClassWeek classWeek : teachingClassWeek) {
                            count += classWeek.getTotalHour();
                        }
                        m.put("lecture", String.valueOf(count));
                    } else {
                        m.put("lecture", String.valueOf(0));
                    }


                    List<TeachingClassWeek> teachingClassWeek1 = teachingClassWeekList.stream().filter(p -> p.getHourType().equals(2)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teachingClassWeek1)) {
                        int count = 0;
                        for (TeachingClassWeek classWeek : teachingClassWeek1) {
                            count += classWeek.getTotalHour();
                        }

                        m.put("experiment", String.valueOf(count));
                    } else {
                        m.put("experiment", String.valueOf(0));
                    }


                    List<TeachingClassWeek> teachingClassWeek2 = teachingClassWeekList.stream().filter(p -> p.getHourType().equals(4)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teachingClassWeek2)) {
                        int count = 0;
                        for (TeachingClassWeek classWeek : teachingClassWeek2) {
                            count += classWeek.getTotalHour();
                        }
                        m.put("other", String.valueOf(count));
                    } else {
                        m.put("other", String.valueOf(0));
                    }

                    int weekNum = teachingClassWeekList.stream().mapToInt(TeachingClassWeek::getWeekNum).sum() / teachingClassWeekList.size();

                    m.put("weekNum", String.valueOf(weekNum));


                    List<String> weeks = teachingClassWeekList.stream().map(TeachingClassWeek::getWeek).collect(Collectors.toList());
                    String s = weeks.get(0);
                    char[] chars = s.toCharArray();
                    StringBuilder s1 = new StringBuilder();
                    for (int i = 0; i < chars.length; i++) {
                        s1.append("0");
                    }
                    s = s1.toString();


                    for (String week : weeks) {
                        char[] chars1 = week.toCharArray();
                        StringBuilder s2 = new StringBuilder();
                        for (int i = 0; i < chars1.length; i++) {
                            if (s.charAt(i) == 0 && week.charAt(i) == 0) {
                                s2.append("0");
                            } else {
                                s2.append("1");
                            }
                        }
                        s = s2.toString();
                    }

                    if (StringUtils.isNotBlank(s)) {
                        char[] chars2 = s.toCharArray();
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < chars2.length; i++) {
                            if (chars[i] == '1') {
                                sb.append((i + 1) + ",");
                            }
                        }
                        String s2 = sb.toString();
                        s = s2.substring(0, s2.length() - 1) + "周";
                        m.put("week", s);
                    }
                }
            } else {
                List<TeachingClassWeek> teachingClassWeekList = teachingClass.getTeachingClassWeeks();
                if (CollUtil.isNotEmpty(teachingClassWeekList)) {

                    List<String> weeks = teachingClassWeekList.stream().map(TeachingClassWeek::getWeek).collect(Collectors.toList());
                    String s = weeks.get(0);
                    char[] chars = s.toCharArray();
                    StringBuilder s1 = new StringBuilder();
                    for (int i = 0; i < chars.length; i++) {
                        s1.append("0");
                    }
                    s = s1.toString();


                    for (String week : weeks) {
                        char[] chars1 = week.toCharArray();
                        StringBuilder s2 = new StringBuilder();
                        for (int i = 0; i < chars1.length; i++) {
                            if (s.charAt(i) == 0 && week.charAt(i) == 0) {
                                s2.append("0");
                            } else {
                                s2.append("1");
                            }
                        }
                        s = s2.toString();
                    }

                    if (StringUtils.isNotBlank(s)) {
                        char[] chars2 = s.toCharArray();
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < chars2.length; i++) {
                            if (chars[i] == '1') {
                                sb.append((i + 1) + ",");
                            }
                        }
                        String s2 = sb.toString();
                        s = s2.substring(0, s2.length() - 1) + "周";
                        m.put("week", s);
                    }
                }
            }

            m.put("assessment", teachingClass.getAssessmentName());
            m.put("11", "/");
            m.put("22", "/");
            List<TeachingClassTeacher> teachingClassTeachers1 = teachingClass.getTeachingClassTeachers();
            if (CollUtil.isNotEmpty(teachingClassTeachers1)) {
                List<Long> teacherIds = teachingClassTeachers1.stream().map(TeachingClassTeacher::getTeacherId).distinct().collect(Collectors.toList());
                String teacherName = teacherList.stream().filter(p -> teacherIds.contains(p.getTeacherId())).map(Teacher::getTeacherName).collect(Collectors.joining("、"));
                m.put("teachers", teacherName);
            }
            m.put("mixClass", "1");

            m.put("reserve", "");
            rowList.add(m);
        }

        ExcelPoiUtil excelTool = new ExcelPoiUtil("List<Map>多级表头");
        Map<String, String> param = ImmutableMap.<String, String>builder().put("id", "id").put("pid", "pid")
                .put("content", "content").put("fieldName", "fieldName").put("width", "width").build();
        List<ColEntity> titleData = null;
        try {
            titleData = excelTool.colEntityTransformer(titleList, param, "0");
        } catch (Exception e) {
            e.printStackTrace();
        }
        heads.put("教学班数据导出", titleData);// 每个sheet的表头，sheet名称为key
        datas.put("教学班数据导出", rowList);// 每个sheet的内容，sheet名称为key
        types.put("教学班数据导出", 0);// 每个sheet的样式类型，sheet名称为key

    }


    @Override
    public void exportOfTheStartPlan(HttpServletResponse response, Integer taskId, String collegeName, String gradeName, String majorName, String courseTypeName, String courseNatureName, String stateName, CourseVo param) {


        List<ExcelStartPlan> excelStartPlans = new ArrayList<>();

        param.setCurrentPage(1);
        param.setPageSize(1000000);

        CourseAndApplyDto courseAndApply = planTeachingService.getCourseAndApply(param, taskId);

        TaskInfo taskInfo = taskInfoService.getById(taskId);
        List<CourseVo> list = courseAndApply.getCourseVoList();


        list.forEach(o -> {
            ExcelStartPlan excelStartPlan = new ExcelStartPlan();

            excelStartPlan.setCourseName(o.getCourseName());
            excelStartPlan.setCourseCode(o.getCourseCode());
            excelStartPlan.setCourseType(o.getCourseType());
            excelStartPlan.setCourseNature(o.getCourseNature().equals(1) ? "必修" : "选修");
            excelStartPlan.setCred(o.getCredit());
            List<ExcelHourType> excelHourTypes = new ArrayList<>();
            List<CourseWeek> courseWeeks = o.getCourseWeeks();
            if (!CollUtil.isEmpty(courseWeeks)) {
                courseWeeks.forEach(cw -> {
                    ExcelHourType excelHourType = new ExcelHourType();
                    excelHourType.setHourType(cw.getHourTypeName());
                    excelHourType.setTotalHour(cw.getTotalHour());
                    excelHourTypes.add(excelHourType);
                });
            }
            excelStartPlan.setExcelHourTypes(excelHourTypes);
            excelStartPlan.setCollegeName(o.getCollegeName());
            excelStartPlan.setGradeName(o.getGradeName());
            excelStartPlan.setMajorName(o.getMajorName());
            excelStartPlan.setState(StringUtils.isNotBlank(o.getDescription()) ? o.getDescription() : "正常开课");
            excelStartPlans.add(excelStartPlan);

        });

        //构建标题
        String title = " {} {}确认教学任务按教学班导出" + "\n" + "院系:{}" + "\n" + "年级:{}" + "\n" + "专业:{}" + "\n" + "课程类别:{}"
                + "\n" + "课程性质:{}" + "\n" + "变更状态:{}";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                , StringUtils.isNotBlank(collegeName) ? collegeName : "全部院系"
                , StringUtils.isNotBlank(gradeName) ? gradeName : "全部年级"
                , StringUtils.isNotBlank(majorName) ? gradeName : "全部专业",
                StringUtils.isNotBlank(courseTypeName) ? courseTypeName : "全部课程类别"
                , StringUtils.isNotBlank(courseNatureName) ? courseNatureName : "全部课程性质"
                , StringUtils.isNotBlank(stateName) ? stateName : "全部变更状态");


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelStartPlans,
                format,
                "确认开课计划",
                ExcelStartPlan.class,
                "确认开课计划导出" + time + ".xls", response);


    }


    @Override
    public void exportOfTeachingGroup(HttpServletResponse response, String collegeName, Integer taskId, String baseCollegeId, String keyword) {


        List<ExcelTeachingClassGroup> excelTeachingClasses = new ArrayList<>();


        TaskInfo taskInfo = taskInfoService.getById(taskId);


        Page<SubClass> page = new Page<>(1, 100000);
        page.setOptimizeCountSql(false);
        PageInfo<SubClass> subTeachingClassHourList = subClassService.getSubTeachingClassHourList(page, taskId, keyword, baseCollegeId);


        List<SubClass> list = subTeachingClassHourList.getList();

        list.forEach(o -> {

            ExcelTeachingClassGroup excelTeachingClassGroup = new ExcelTeachingClassGroup();

            excelTeachingClassGroup.setGroupName(o.getCourseName());


            List<TeachingClassGroupExcelVo> teachingClassGroupExcelVos = new ArrayList<>();
            List<List<SubClassGroup>> subClassGroupList = o.getSubClassGroupList();
            subClassGroupList.forEach(sg -> {
                TeachingClassGroupExcelVo teachingClassGroupExcelVo = new TeachingClassGroupExcelVo();
                List<SubClassGroup> m = sg;

                List<TeachingClassGroupExcelDto> teachingClassGroupExcelDtos = new ArrayList<>();
                m.forEach(n -> {
                    teachingClassGroupExcelVo.setTeachingClassGroupName(n.getGroupName());
                    TeachingClassGroupExcelDto teachingClassGroupExcelDto = new TeachingClassGroupExcelDto();

                    teachingClassGroupExcelDto.setGroupTeachingClassName(n.getTeachingClassName());
                    teachingClassGroupExcelDto.setCourseName(n.getCourseName());
                    teachingClassGroupExcelDto.setCollegeName(n.getTeachingClassHourVo().getCollegeName());
                    teachingClassGroupExcelDto.setClassNum(n.getTeachingClassHourVo().getStudentNumber());
                    teachingClassGroupExcelDto.setAssessMethod(n.getTeachingClassHourVo().getAssessmentName());
                    teachingClassGroupExcelDto.setHourType(n.getTeachingClassHourVo().getHourTypeName());
                    if (!CollUtil.isEmpty(n.getTeachingClassHourVo().getTeachers())) {
                        List<TeacherDto> teachers = n.getTeachingClassHourVo().getTeachers();
                        List<TeacherDto> teacherDtos = teachers.stream().filter(p -> p.getIdentity().equals(1)).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(teacherDtos)) {
                            String teacherName = teacherDtos.stream().map(TeacherDto::getTeacherName).collect(Collectors.joining(","));
                            teachingClassGroupExcelDto.setTeacherNo(teacherName);
                        }

                        List<TeacherDto> teacherDtos1 = teachers.stream().filter(p -> p.getIdentity().equals(2)).collect(Collectors.toList());
                        if (CollUtil.isNotEmpty(teacherDtos1)) {
                            String teacherName = teacherDtos1.stream().map(TeacherDto::getTeacherName).collect(Collectors.joining(","));
                            teachingClassGroupExcelDto.setAssTeacherNo(teacherName);
                        }
                    }

                    teachingClassGroupExcelDto.setRoomType(n.getTeachingClassHourVo().getRoomTypeName());
                    teachingClassGroupExcelDto.setRoomName(n.getTeachingClassHourVo().getRoomName());
                    if (StringUtils.isNotBlank(n.getTeachingClassHourVo().getWeek())) {
                        int i = n.getTeachingClassHourVo().getWeek().indexOf('1') + 1;
                        int j = n.getTeachingClassHourVo().getWeek().lastIndexOf('1') + 1;
                        teachingClassGroupExcelDto.setWeek(i + "-" + j + "周");
                    }

                    teachingClassGroupExcelDto.setTotalHour(n.getTeachingClassHourVo().getTotalHour());
                    teachingClassGroupExcelDto.setWeekNum(n.getTeachingClassHourVo().getWeekNum());

                    teachingClassGroupExcelDto.setConnectSection(n.getTeachingClassHourVo().getConnectSection());
                    teachingClassGroupExcelDto.setConnectNumber(n.getTeachingClassHourVo().getConnectNumber());

                    teachingClassGroupExcelDtos.add(teachingClassGroupExcelDto);

                });
                teachingClassGroupExcelVo.setTeachingClassGroupExcelDtos(teachingClassGroupExcelDtos);
                teachingClassGroupExcelVos.add(teachingClassGroupExcelVo);
            });
            excelTeachingClassGroup.setTeachingClassGroupExcelVos(teachingClassGroupExcelVos);

            excelTeachingClasses.add(excelTeachingClassGroup);
        });


        //构建标题
        String title = " {} {}确认教学任务按教学班导出" + "\n" + "院系:{}";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                , StringUtils.isNotBlank(collegeName) ? collegeName : "全部院系");


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelTeachingClasses,
                format,
                "按分组",
                ExcelTeachingClassGroup.class,
                "确认教学任务按分组导出" + time + ".xls", response);


    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importTeachingClassDifferentLevels(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file, String baseCollegeId, String baseCourseId) {
        List<ExcelTeachingClassDifferentLevels> excelTeachingActivities = this.readTeachingClassDifferentLevels(file);


        Course one = courseService.lambdaQuery().eq(Course::getTaskId, taskId).eq(Course::getBaseCourseId, baseCourseId).one();
        if (flag == 2) {
            List<TeachingClass> list = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId)
                    .eq(TeachingClass::getBaseCollegeId, one.getBaseCollegeId())
                    .eq(TeachingClass::getCourseId, one.getCourseId())
                    .eq(TeachingClass::getTeachingClassType, 0).list();
            if (CollUtil.isNotEmpty(list)) {
                List<Long> ids = list.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());
                teachingClassService.lambdaUpdate().eq(TeachingClass::getTaskId, taskId).in(TeachingClass::getTeachingClassId, ids).remove();
                teachingClassWeekService.lambdaUpdate().in(TeachingClassWeek::getTeachingClassId, ids).remove();
                teachingClassTeacherService.lambdaUpdate().in(TeachingClassTeacher::getTeachingClassId, ids).remove();
                teachingClassStudentService.lambdaUpdate().in(TeachingClassStudent::getTeachingClassId, ids).remove();
            }
        }

        List<PlanTeachingCourse> planTeachingCourses = planTeachingCourseService.lambdaQuery()
                .eq(PlanTeachingCourse::getTaskId, taskId)
                .eq(PlanTeachingCourse::getBaseCourseId, one.getBaseCourseId()).list();

        if (CollUtil.isNotEmpty(planTeachingCourses)) {
            List<String> baseTeachingPlanIds = planTeachingCourses.stream().map(PlanTeachingCourse::getBaseTeachingPlanId).distinct().collect(Collectors.toList());

            List<PlanTeaching> planTeachings = planTeachingService.lambdaQuery().eq(PlanTeaching::getTaskId, taskId)
                    .in(PlanTeaching::getBaseTeachingPlanId, baseTeachingPlanIds).list();

            List<String> baseStudentIds = new ArrayList<>();

            if (CollUtil.isNotEmpty(planTeachings)) {
                List<String> planTeachingClassIds = planTeachings.stream().map(PlanTeaching::getBaseTeachingPlanId).distinct().collect(Collectors.toList());
                baseStudentIds = planTeachingStudentService.lambdaQuery()
                        .eq(PlanTeachingStudent::getTaskId, taskId).in(PlanTeachingStudent::getBaseTeachingPlanId, planTeachingClassIds).list()
                        .stream().map(PlanTeachingStudent::getBaseStudentId).collect(Collectors.toList());

            }

            Map<String, Campus> campusMap = campusService.lambdaQuery().eq(Campus::getTaskId, taskId).list().stream().collect(Collectors.toMap(Campus::getCampusName, Function.identity(), (o1, o2) -> o1));


            List<CourseWeek> courseWeeks = courseWeekService.lambdaQuery().eq(CourseWeek::getCourseId, one.getCourseId()).list();

            Map<String, Course> courseMap = courseService.lambdaQuery().eq(Course::getTaskId, taskId).list().stream()
                    .collect(Collectors.toMap(Course::getBaseCourseId, Function.identity(), (o1, o2) -> o1));


            Map<String, Student> studentMap = new HashMap<>();
            if (CollUtil.isNotEmpty(baseStudentIds)) {
                studentMap = studentService.lambdaQuery().eq(Student::getTaskId, taskId).in(Student::getBaseStudentId, baseStudentIds).list().stream()
                        .collect(Collectors.toMap(Student::getBaseStudentId, Function.identity(), (o1, o2) -> o1));
            }
            Long index = 3L;
            for (ExcelTeachingClassDifferentLevels excelTeachingActivity : excelTeachingActivities) {
                excelTeachingActivity.setId(index);
                index++;
            }


            List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
            for (ExcelTeachingClassDifferentLevels excelTeachingActivity : excelTeachingActivities) {

                if (StringUtils.isBlank(excelTeachingActivity.getStudentIds())) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                    errorExcelVo.setErrorMsg(excelTeachingActivity.getTeachingClassName() + "学生未设置");
                    errorExcelVos.add(errorExcelVo);
                } else {
                    List<String> studentIds = new ArrayList<>(Arrays.asList(excelTeachingActivity.getStudentIds().split("\\|")));

                    List<String> finalBaseStudentIds = baseStudentIds;
                    studentIds.forEach(o -> {
                        if (StringUtils.isBlank(o) || !finalBaseStudentIds.contains(o.trim())) {
                            ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                            errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                            errorExcelVo.setErrorMsg(o + "学生不存在");
                            errorExcelVos.add(errorExcelVo);
                        }
                    });
                }


                if (StringUtils.isBlank(excelTeachingActivity.getCampusName())) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                    errorExcelVo.setErrorMsg(excelTeachingActivity.getTeachingClassName() + "校区未设置");
                    errorExcelVos.add(errorExcelVo);
                } else {
                    if (ObjUtil.isNull(campusMap.get(excelTeachingActivity.getCampusName()))) {
                        ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                        errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                        errorExcelVo.setErrorMsg(excelTeachingActivity.getTeachingClassName() + "校区不存在");
                        errorExcelVos.add(errorExcelVo);
                    }
                }


            }


            Integer errorExcelVos1 = errorExcelVos.size();
            if (CollUtil.isNotEmpty(errorExcelVos)) {
                String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
                response.setCharacterEncoding("UTF-8");
                response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

                MyExcelUtils.exportExcel(errorExcelVos,
                        "分级导入信息错误",
                        "错误信息",
                        ErrorExcelVo.class,
                        "分级导入信息错误" + time + ".xls", response);
                throw new BizException("分级导入信息错误");
            }

            if (errorExcelVos1 == 0) {

                List<TeachingClass> teachingClasses = new ArrayList<>();

                PlanTeaching planTeaching = planTeachings.get(0);

                for (ExcelTeachingClassDifferentLevels excelTeachingActivity : excelTeachingActivities) {

                    TeachingClass teachingClass = new TeachingClass();
                    teachingClass.setTaskId(taskId);
                    teachingClass.setTeachingClassName(excelTeachingActivity.getTeachingClassName());
                    teachingClass.setCourseId(courseMap.get(baseCourseId).getCourseId());
                    teachingClass.setCourseName(courseMap.get(baseCourseId).getCourseName());
                    teachingClass.setBaseCollegeId(courseMap.get(baseCourseId).getBaseCollegeId());
                    teachingClass.setCollegeName(courseMap.get(baseCourseId).getCollegeName());
                    teachingClass.setFlag(one.getFlag());
                    teachingClass.setBaseMajorId(planTeaching.getBaseMajorId());
                    teachingClass.setMajorName(planTeaching.getMajorName());
                    List<String> stIds = new ArrayList<>(Arrays.asList(excelTeachingActivity.getStudentIds().split("\\|")));
                    teachingClass.setClassNum(stIds.size());
                    teachingClass.setTeachingClassType(0);
                    teachingClass.setFlag(courseMap.get(baseCourseId).getFlag());
                    teachingClass.setGradeId(planTeaching.getGradeId());
                    teachingClass.setGradeName(planTeaching.getGradeName());

                    teachingClass.setCampusId(campusMap.get(excelTeachingActivity.getCampusName()).getCampusId());
                    teachingClass.setCampusName(campusMap.get(excelTeachingActivity.getCampusName()).getCampusName());

                    teachingClass.setStudyNature(courseMap.get(baseCourseId).getCourseNature());
                    teachingClass.setMajorProp(courseMap.get(baseCourseId).getMajorProp());
                    teachingClass.setIsEnable(0);
                    teachingClass.setIsOptional(0);
                    teachingClasses.add(teachingClass);
                }

                teachingClassService.saveOrUpdateBatch(teachingClasses);


                List<TeachingClassStudent> teachingClassStudents = new ArrayList<>();
                Map<String, Student> finalStudentMap = studentMap;
                teachingClasses.forEach(o -> {
                    ExcelTeachingClassDifferentLevels excelTeachingClassDifferentLevels = excelTeachingActivities.stream().filter(p -> p.getTeachingClassName().equals(o.getTeachingClassName())).findFirst().orElse(null);
                    if (ObjUtil.isNotNull(excelTeachingClassDifferentLevels)) {
                        List<String> studentId = new ArrayList<>(Arrays.asList(excelTeachingClassDifferentLevels.getStudentIds().split("\\|")));

                        studentId.forEach(s -> {
                            TeachingClassStudent teachingClassStudent = new TeachingClassStudent();
                            teachingClassStudent.setTeachingClassId(o.getTeachingClassId());
                            teachingClassStudent.setCourseId(courseMap.get(baseCourseId).getCourseId());
                            teachingClassStudent.setStudentId(finalStudentMap.get(s).getStudentId());
                            teachingClassStudent.setFlag(1);
                            teachingClassStudents.add(teachingClassStudent);

                        });
                    }
                });
                teachingClassStudentService.saveOrUpdateBatch(teachingClassStudents);


                List<TeachingClassWeek> teachingClassWeeks = new ArrayList<>();


                WeekDateVo dateVo = taskInfoService.countWeek(taskId);

                StringBuilder str = new StringBuilder();
                for (long i = 0; i < dateVo.getWeekCount(); i++) {
                    str.append("1");
                }
                String string = str.toString();


                teachingClasses.forEach(o -> {
                    courseWeeks.forEach(c -> {
                        TeachingClassWeek teachingClassWeek = new TeachingClassWeek();
                        teachingClassWeek.setTeachingClassId(o.getTeachingClassId());
                        teachingClassWeek.setWeek(StringUtils.isNotBlank(c.getWeek()) ? c.getWeek() : string);
                        teachingClassWeek.setTotalHour(c.getTotalHour());
                        teachingClassWeek.setWeekNum(c.getWeekNum());
                        teachingClassWeek.setConnectSection(c.getConnectSection());
                        teachingClassWeek.setConnectNumber(c.getConnectNumber());
                        teachingClassWeek.setHourType(c.getHourType());
                        teachingClassWeeks.add(teachingClassWeek);
                    });
                });

                teachingClassWeekService.saveOrUpdateBatch(teachingClassWeeks);

            }
        }
    }

    private List<ExcelTeachingClassDifferentLevels> readTeachingClassDifferentLevels(MultipartFile file) {
        List<ExcelTeachingClassDifferentLevels> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "教学班名称", "校区", "学生学号");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("教学班名称", "teachingClassName");
            reader.addHeaderAlias("校区", "campusName");
            reader.addHeaderAlias("学生学号", "studentIds");

            excelTeachingActivities = reader.read(1, 2, ExcelTeachingClassDifferentLevels.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;

    }


    @Override
    public void exportConfirmByClass(HttpServletResponse response, String cssRoundName, String collegeName, String courseTypeName, String courseNature, String courseName, String baseCollegeId, Long courseId, Integer flag, String keyword, Integer pageSize, Integer currentPage, Integer taskId, Integer roundId) {


        List<ExcelConfirmByClass> excelConfirmByClasses = new ArrayList<>();

        List<Teacher> teachers = teacherService.lambdaQuery().eq(Teacher::getTaskId, taskId).list();

        //任课教师
        List<Teacher> teachers1 = teachers.stream().filter(p -> p.getIdentity().equals(1)).collect(Collectors.toList());

        //助教教师
        List<Teacher> teachers2 = teachers.stream().filter(p -> p.getIdentity().equals(2)).collect(Collectors.toList());

        List<TeachingClassStudent> teachingClassStudents = teachingClassStudentService.lambdaQuery().eq(TeachingClassStudent::getRoundId, roundId).list();

        List<Student> students = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();


        ResultDto<TeachingClass> studentRetakeClass = selectCourseService.getStudentRetakeClass(baseCollegeId, courseId, keyword, 1000000, 1, taskId, flag, roundId);


        Map<Long, List<TeachingClass>> courseMap = studentRetakeClass.getList().stream().collect(Collectors.groupingBy(TeachingClass::getCourseId));


        courseMap.forEach((key, value) -> {

            ExcelConfirmByClass excelConfirmByClass = new ExcelConfirmByClass();
            TeachingClass teachingClass = value.get(0);
            excelConfirmByClass.setCourseName(teachingClass.getCourseName());
            List<TeachingClassExcelVo> teachingClassExcelVoList = new ArrayList<>();
            value.forEach(o -> {
                TeachingClassExcelVo teachingClassExcelVo = new TeachingClassExcelVo();
                teachingClassExcelVo.setTeachingClassName(o.getTeachingClassName());

                List<TeachingClassTeacher> teachingClassTeachers = o.getTeachingClassTeachers();
                if (CollUtil.isNotEmpty(teachingClassTeachers)) {
                    List<Long> teacherIds = teachingClassTeachers.stream().map(TeachingClassTeacher::getTeacherId).distinct().collect(Collectors.toList());
                    List<Teacher> teacherList = teachers1.stream().filter(p -> teacherIds.contains(p.getTeacherId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teacherList)) {

                        String collect = teacherList.stream().map(Teacher::getTeacherName).collect(Collectors.joining(","));
                        teachingClassExcelVo.setTeacherName(collect);
                    }

                    List<Teacher> teacherList1 = teachers2.stream().filter(p -> teacherIds.contains(p.getTeacherId())).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teacherList1)) {
                        String collect = teacherList1.stream().map(Teacher::getTeacherName).collect(Collectors.joining(","));
                        teachingClassExcelVo.setIdentifyTeacherName(collect);
                    }
                }
                teachingClassExcelVo.setCourseType(o.getCourseType());
                teachingClassExcelVo.setCourseNature(o.getCourseNature().equals(1) ? "必修" : "选修");
                teachingClassExcelVo.setClassNum(o.getClassNum());
                teachingClassExcelVo.setOpenClass(o.getLimitClassNum());
                teachingClassExcelVo.setSelectNum(o.getStudentIds().size());

                List<StudentExcelVo> studentExcelVos = new ArrayList<>();
                List<Long> studentIds = o.getStudentIds();

                if (CollUtil.isNotEmpty(studentIds)) {
                    studentIds.forEach(s -> {
                        Student student = students.stream().filter(p -> p.getStudentId().equals(s)).findFirst().orElse(null);
                        if (ObjUtil.isNotNull(student)) {
                            StudentExcelVo studentExcelVo = new StudentExcelVo();
                            studentExcelVo.setClassName(student.getClassName());
                            studentExcelVo.setCollegeName(student.getCollegeName());
                            studentExcelVo.setGradeName(student.getGradeName());
                            studentExcelVo.setStudentName(student.getStudentName());
                            studentExcelVo.setStudentNo(student.getBaseStudentId());
                            TeachingClassStudent teachingClassStudent = teachingClassStudents.stream().filter(p -> p.getTeachingClassId().equals(o.getTeachingClassId()) && p.getStudentId().equals(student.getStudentId())).findFirst().orElse(null);
                            if (ObjUtil.isNotNull(teachingClassStudent)) {
                                studentExcelVo.setTime(teachingClassStudent.getModifiedTime());
                            }
                            studentExcelVos.add(studentExcelVo);
                        }
                    });
                }
                teachingClassExcelVo.setStudentExcelVos(studentExcelVos);
                teachingClassExcelVoList.add(teachingClassExcelVo);
            });
            excelConfirmByClass.setTeachingClassExcelVoList(teachingClassExcelVoList);
            excelConfirmByClasses.add(excelConfirmByClass);
        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);
        //构建标题
        String title = " {} {}按教学班确认导出" + "\n" + "选课轮次:{}" + "\n" + "院系:{}" + "\n" + "课程类别:{}" + "\n" + "课程性质:{}" + "\n" + "课程名称:{}";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                , cssRoundName, StringUtils.isNotBlank(collegeName) ? collegeName : "全部院系",
                StringUtils.isNotBlank(courseTypeName) ? courseTypeName : "全部课程类别",
                StringUtils.isNotBlank(courseNature) ? courseNature : "全部课程性质",
                StringUtils.isNotBlank(courseName) ? courseName : "全部课程");


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");


        MyExcelUtils.exportExcel(excelConfirmByClasses,
                format,
                "按教学班确认",
                ExcelConfirmByClass.class,
                "按教学班确认导出" + time + ".xls", response);
    }


    @Override
    public void exportConfirmByStudent(HttpServletResponse response, String cssRoundName, String collegeName, String courseTypeName, String courseNature, String courseName, String baseCollegeId, String gradeId, String classId, String keyword, Integer flag, Integer pageSize, Integer currentPage, Integer taskId, Integer needToSelect, Integer roundId) {

        List<ExcelConfirmByStudent> excelConfirmByStudents = new ArrayList<>();


        List<TeachingClassStudent> teachingClassStudents = teachingClassStudentService.lambdaQuery().eq(TeachingClassStudent::getRoundId, roundId).list();


        List<TeachingClass> teachingClasses = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).list();

        ResultDto<StudentSelectInfoDto> studentSelectList = selectCourseService.getStudentSelectList(baseCollegeId, gradeId, classId, keyword, 100000, 1, taskId, needToSelect, flag, roundId);


        studentSelectList.getList().forEach(o -> {
            ExcelConfirmByStudent excelConfirmByClass = new ExcelConfirmByStudent();
            excelConfirmByClass.setStudentName(o.getStudentName());
            excelConfirmByClass.setCollegeName(o.getCollegeName());
            excelConfirmByClass.setStudentId(o.getBaseStudentId());
            excelConfirmByClass.setGradeName(o.getGradeName());
            excelConfirmByClass.setClassName(o.getClassName());
            excelConfirmByClass.setCourseNums(o.getNeedNum());
            excelConfirmByClass.setSelectCourseNums(o.getSelectNum());
            List<CourseExcelVo> courseExcelVos = new ArrayList<>();

            List<Long> teachingClassIds = teachingClassStudents.stream().filter(p -> p.getStudentId().equals(o.getStudentId())).map(TeachingClassStudent::getTeachingClassId).collect(Collectors.toList());
            if (CollUtil.isNotEmpty(teachingClassIds)) {

                teachingClassIds.forEach(t -> {
                    TeachingClass teachingClass = teachingClasses.stream().filter(p -> p.getTeachingClassId().equals(t)).findFirst().orElse(null);
                    if (ObjUtil.isNotNull(teachingClass)) {
                        CourseExcelVo courseExcelVo = new CourseExcelVo();
                        courseExcelVo.setCourseName(teachingClass.getCourseName());
                        courseExcelVo.setTeachingClassName(teachingClass.getTeachingClassName());
                        courseExcelVos.add(courseExcelVo);
                    }
                });
            }
            excelConfirmByClass.setCourseExcelVos(courseExcelVos);
            excelConfirmByStudents.add(excelConfirmByClass);

        });


        TaskInfo taskInfo = taskInfoService.getById(taskId);
        //构建标题
        String title = " {} {}按学生确认导出" + "\n" + "选课轮次:{}" + "\n" + "院系:{}" + "\n" + "课程类别:{}" + "\n" + "课程性质:{}" + "\n" + "课程名称:{}";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName()
                , cssRoundName, StringUtils.isNotBlank(collegeName) ? collegeName : "全部院系",
                StringUtils.isNotBlank(courseTypeName) ? courseTypeName : "全部课程类别",
                StringUtils.isNotBlank(courseNature) ? courseNature : "全部课程性质",
                StringUtils.isNotBlank(courseName) ? courseName : "全部课程");


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");


        MyExcelUtils.exportExcel(excelConfirmByStudents,
                format,
                "按教学班确认",
                ExcelConfirmByStudent.class,
                "按学生确认导出" + time + ".xls", response);
    }


    @Override
    public void exportCourseRule(HttpServletResponse response, Integer taskId, Integer dataRange, String baseCollegeId, String courseTypeId, Integer courseNature, Integer flag, String keyword, Integer parameterSet, Integer currentPage, Integer pageSize) {

        List<ExcelCourseRule> excelCourseRules = new ArrayList<>();

        Page<Course> page = new Page<>(1, 10000);
        SetCourseDto<Course> courseList = courseService.getCourseList(page, taskId, dataRange, baseCollegeId, courseTypeId, courseNature, flag, keyword, parameterSet);

        List<Course> list = courseList.getList();


        for (Course course : list) {
            if (course.getCourseLimit().equals(0)) {
                continue;
            }

            ExcelCourseRule excelCourseRule = new ExcelCourseRule();

            excelCourseRule.setCourseName(course.getCourseName());

            excelCourseRule.setCourseCode(course.getCourseCode());

            excelCourseRule.setCollegeName(course.getCollegeName());

            excelCourseRule.setCourseType(course.getCourseType());

            excelCourseRule.setCourseNature(course.getCourseNature().equals(1) ? "必修" : "选修");

            excelCourseRule.setCourseLimit(String.valueOf(course.getCourseLimit()));

            excelCourseRules.add(excelCourseRule);
        }

        TaskInfo taskInfo = taskInfoService.getById(taskId);

        //构建标题
        String title = " {} {}课程规则导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelCourseRules,
                format,
                "课程信息规则导出",
                ExcelCourseRule.class,
                "课程信息规则导出" + time + ".xls", response);
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importCourseRule(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {


        List<ExcelCourseRule> excelTeachingActivities = this.readForbiddenOfCourse(file);


        Page<Course> page = new Page<>(1, 10000);
        SetCourseDto<Course> courseList = courseService.getCourseList(page, taskId, 0, null, null, null, 1, null, null);

        List<Course> list = courseList.getList();


        Long index = 3L;
        for (ExcelCourseRule excelTeachingActivity : excelTeachingActivities) {
            excelTeachingActivity.setId(index);
            index++;
        }


        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();
        for (ExcelCourseRule excelTeachingActivity : excelTeachingActivities) {


            Course course = list.stream().filter(p -> p.getCourseName().equals(excelTeachingActivity.getCourseName()) && p.getCourseCode().equals(excelTeachingActivity.getCourseCode())).findFirst().orElse(null);
            if (ObjUtil.isNull(course)) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelTeachingActivity.getId());
                errorExcelVo.setErrorMsg(excelTeachingActivity.getCourseName() + "课程不存在");
                errorExcelVos.add(errorExcelVo);
            }


        }

        Integer errorExcelVos1 = errorExcelVos.size();
        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入课程规则错误",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入课程规则错误" + time + ".xls", response);
            throw new BizException("导入课程规则错误");
        }

        if (errorExcelVos1 == 0) {
            List<Course> courses = new ArrayList<>();

            for (ExcelCourseRule excelTeachingActivity : excelTeachingActivities) {

                Course course = list.stream().filter(p -> p.getCourseName().equals(excelTeachingActivity.getCourseName()) && p.getCourseCode().equals(excelTeachingActivity.getCourseCode())).findFirst().orElse(null);
                if (ObjUtil.isNotNull(course)) {
                    course.setCourseLimit(Integer.parseInt(excelTeachingActivity.getCourseLimit()));
                    courses.add(course);
                }

            }

            if (CollUtil.isNotEmpty(courses)) {
                courseService.saveOrUpdateBatch(courses);
            }

        }

    }

    @Override
    public void exportSubClass(HttpServletResponse response, Integer taskId, String keyword, Integer currentPage, Integer pageSize) {
//
//
//        List<ExcelSubClassDto> excelCourseRules = new ArrayList<>();
//
//
//        PageInfo<SplitClass> splitClassList = splitClassService.getSplitClassList(currentPage, pageSize, taskId, keyword);
//
//        List<SplitClass> list = splitClassList.getList();
//
//
//        for (SplitClass splitClass : list) {
//
//            ExcelSubClassDto excelSubClassDto = new ExcelSubClassDto();
//
//            excelSubClassDto.setSubName(splitClass.getSplitName());
//            excelSubClassDto.setSubClassName(splitClass.getClassName());
//            List<ExcelSubCourse> excelSubCourses  = new ArrayList<>();
//            List<TeachingClass> teachingClassList = splitClass.getTeachingClassList();
//
//            Map<Long, List<TeachingClass>> teachingClassMap = teachingClassList.stream().collect(Collectors.groupingBy(TeachingClass::getCourseId));
//
//            teachingClassMap.forEach((key,value)->{
//                ExcelSubCourse excelSubCourse = new ExcelSubCourse();
//                TeachingClass teachingClass = value.get(0);
//                excelSubCourse.setSubCourse(teachingClass.getCourseName());
//                List<ExcelSubClassVo> excelSubClassVos = new ArrayList<>();
//                value.forEach(o->{
//                    ExcelSubClassVo excelSubClassVo = new ExcelSubClassVo();
//                    excelSubClassVo.setSubClassVo(o.getTeachingClassName());
//                    List<ExcelSubClassHourType> excelSubClassHourTypes = new ArrayList<>();
//                    List<TeachingClassWeek> teachingClassWeeks = o.getTeachingClassWeeks();
//                    List<TeachingClassTeacher> teachingClassTeachers = o.getTeachingClassTeachers();
//                    teachingClassWeeks.forEach(tw->{
//                        ExcelSubClassHourType excelSubClassHourType = new ExcelSubClassHourType();
//                        excelSubClassHourType.setSubHourType(tw.getHourType().equals(1)?"讲授":tw.getHourType().equals(2)?"实验":tw.getHourType().equals(3)?"上机":"其他");
//                        excelSubClassHourType.setSubRoom(tw.getRoomName());
//                        String teacherName = teachingClassTeachers.stream().filter(p -> p.getHourType().equals(tw.getHourType()) && p.getIdentity().equals(1)).collect(Collectors.toList()).stream()
//                                .map(TeachingClassTeacher::getTeacherName).collect(Collectors.joining(","));
//                        excelSubClassHourType.setSubTeacher(teacherName);
//
//                        String teacherName1 = teachingClassTeachers.stream().filter(p -> p.getHourType().equals(tw.getHourType()) && p.getIdentity().equals(2)).collect(Collectors.toList()).stream()
//                                .map(TeachingClassTeacher::getTeacherName).collect(Collectors.joining(","));
//                        excelSubClassHourType.setSubAssTeacher(teacherName1);
//                        excelSubClassHourTypes.add(excelSubClassHourType);
//                    });
//                    excelSubClassVo.setExcelSubClassHourTypes(excelSubClassHourTypes);
//                    excelSubClassVos.add(excelSubClassVo);
//                });
//                excelSubCourse.setExcelSubClassVos(excelSubClassVos);
//                excelSubCourses.add(excelSubCourse);
//            });
//            excelSubClassDto.setExcelSubCourses(excelSubCourses);
//            excelCourseRules.add(excelSubClassDto);
//        }
//
//        TaskInfo taskInfo = taskInfoService.getById(taskId);
//
//        //构建标题
//        String title = " {} {}拆班导出";
//        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName());
//
//
//        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
//
//        response.setCharacterEncoding("UTF-8");
//        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");
//
//        MyExcelUtils.exportExcel(excelCourseRules,
//                format,
//                "拆班导出",
//                ExcelSubClassDto.class,
//                "拆班导出" + time + ".xls", response);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSubClass(HttpServletResponse response, Integer taskId, Integer flag, MultipartFile file) {

        List<ExcelSubClassNoVo> excelTeachingActivities = this.readImportSubClass(file);

        Long index = 3L;
        for (ExcelSubClassNoVo excelTeachingActivity : excelTeachingActivities) {
            excelTeachingActivity.setId(index);
            index++;
        }

        List<ErrorExcelVo> errorExcelVos = new ArrayList<>();


        List<Student> studentList = studentService.lambdaQuery().eq(Student::getTaskId, taskId).list();


        Map<String, List<Student>> studentClassMap = studentList.stream().collect(Collectors.groupingBy(Student::getClassName));

        List<Course> courses = courseService.lambdaQuery().eq(Course::getTaskId, taskId).eq(Course::getFlag, 1).list();


        Map<String, Room> roomMap = roomService.lambdaQuery().eq(Room::getTaskId, taskId).list().stream().collect(Collectors.toMap(Room::getRoomName, Function.identity(), (o1, o2) -> o1));

        Map<String, Teacher> teacherMap = teacherService.lambdaQuery().eq(Teacher::getTaskId, taskId).list().stream()
                .collect(Collectors.toMap(Teacher::getBaseTeacherId, Function.identity(), (o1, o2) -> o1));


        Map<String, List<ExcelSubClassNoVo>> classMap = excelTeachingActivities.stream().collect(Collectors.groupingBy(ExcelSubClassNoVo::getClassName));

        for (Map.Entry<String, List<ExcelSubClassNoVo>> entry : classMap.entrySet()) {

            ExcelSubClassNoVo excelSubClassNoVo = entry.getValue().get(0);

            if (CollUtil.isEmpty(studentClassMap.get(entry.getKey()))) {
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelSubClassNoVo.getId());
                errorExcelVo.setErrorMsg(excelSubClassNoVo.getClassName() + "行政班不存在");
                errorExcelVos.add(errorExcelVo);
                continue;
            }

            Student student = studentClassMap.get(entry.getKey()).get(0);

            List<String> courseName = entry.getValue().stream().map(ExcelSubClassNoVo::getCourseName).distinct().collect(Collectors.toList());


            List<Course> groupCourse = subClassService.getGroupCourse(taskId, student.getClassId());


            List<String> courseNames = groupCourse.stream().map(Course::getCourseName).collect(Collectors.toList());


            List<String> noCourseName = courseName.stream().filter(p -> !courseNames.contains(p)).collect(Collectors.toList());

            if (CollUtil.isNotEmpty(noCourseName)) {
                String s = String.join(",", noCourseName);
                ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                errorExcelVo.setErrorIndex(excelSubClassNoVo.getId());
                errorExcelVo.setErrorMsg(s + "该班级该课程的学生未设置培养计划，请前往基础教务确认！");
                errorExcelVos.add(errorExcelVo);
                continue;
            }


            entry.getValue().forEach(o -> {

                if (ObjUtil.isNull(roomMap.get(o.getRoom()))) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelSubClassNoVo.getId());
                    errorExcelVo.setErrorMsg(o.getRoom() + "该场地不存在");
                    errorExcelVos.add(errorExcelVo);
                }

                if (StringUtils.isNotBlank(o.getTeacherNo()) && ObjUtil.isNull(teacherMap.get(o.getTeacherNo()))) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelSubClassNoVo.getId());
                    errorExcelVo.setErrorMsg(o.getTeacher() + "该授课老师不存在");
                    errorExcelVos.add(errorExcelVo);
                }


                if (StringUtils.isNotBlank(o.getAssTeacherNo()) && ObjUtil.isNull(teacherMap.get(o.getAssTeacherNo()))) {
                    ErrorExcelVo errorExcelVo = new ErrorExcelVo();
                    errorExcelVo.setErrorIndex(excelSubClassNoVo.getId());
                    errorExcelVo.setErrorMsg(o.getTeacher() + "该助教老师不存在");
                    errorExcelVos.add(errorExcelVo);
                }
            });
        }


        Integer errorExcelVos1 = errorExcelVos.size();
        if (CollUtil.isNotEmpty(errorExcelVos)) {
            String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

            MyExcelUtils.exportExcel(errorExcelVos,
                    "导入拆班信息错误",
                    "错误信息",
                    ErrorExcelVo.class,
                    "导入拆班信息错误" + time + ".xls", response);
            throw new BizException("导入拆班信息错误");
        }

        if (errorExcelVos1 == 0) {


            for (Map.Entry<String, List<ExcelSubClassNoVo>> entry : classMap.entrySet()) {
                List<ExcelSubClassNoVo> value = entry.getValue();
                ExcelSubClassNoVo excelSubClassNoVo = entry.getValue().get(0);


                List<String> courseNames = value.stream().map(ExcelSubClassNoVo::getCourseName).distinct().collect(Collectors.toList());

                List<Course> courseList = courses.stream().filter(p -> courseNames.contains(p.getCourseName())).collect(Collectors.toList());

                List<Long> courseIds = courseList.stream().map(Course::getCourseId).distinct().collect(Collectors.toList());


                List<Student> studentList1 = studentList.stream().filter(p -> StringUtils.isNotBlank(p.getClassId()) && p.getClassName().equals(excelSubClassNoVo.getClassName())).collect(Collectors.toList());
                List<Long> studentIdCollect = studentList1.stream().map(Student::getStudentId).collect(Collectors.toList());
                //分组上课的教学班生成后，原来生成的教学班信息将自动删除掉
                teachingClassStudentService.lambdaUpdate().in(TeachingClassStudent::getCourseId, courseIds)
                        .in(TeachingClassStudent::getStudentId, studentIdCollect).remove();
                List<Long> teachingClassIds = teachingClassStudentService.lambdaQuery().in(TeachingClassStudent::getCourseId, courseIds).list()
                        .stream().map(TeachingClassStudent::getTeachingClassId).collect(Collectors.toList());
                List<Long> needDeleteIds = teachingClassService.lambdaQuery().notIn(CollUtil.isNotEmpty(teachingClassIds), TeachingClass::getTeachingClassId, teachingClassIds)
                        .in(TeachingClass::getCourseId, courseIds).list()
                        .stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());
                teachingClassService.deleteClass(needDeleteIds);
                //单双班学生
                List<Student> singleStu = new ArrayList<>();
                List<Student> doubleStu = new ArrayList<>();
                studentList1.forEach(stu -> {
                    int last = Integer.parseInt(stu.getBaseStudentId().substring(stu.getBaseStudentId().length() - 1));
                    if (last % 2 == 0) {
                        doubleStu.add(stu);
                    } else {
                        singleStu.add(stu);
                    }
                });
                MajorGrade majorGrade = majorGradeService.lambdaQuery().eq(MajorGrade::getGradeId, studentList1.get(0).getGradeId())
                        .eq(MajorGrade::getBaseMajorId, studentList1.get(0).getMajorId())
                        .eq(MajorGrade::getBaseCollegeId, studentList1.get(0).getBaseCollegeId())
                        .eq(MajorGrade::getTaskId, taskId).one();
                List<TeachingClass> classList = new ArrayList<>();
                //教学班对应学生
                List<TeachingClassStudent> teachingClassStudentList = new ArrayList<>();
                UUID uuid = UUID.randomUUID();
                for (Course course : courseList) {
                    TeachingClass singleClass = new TeachingClass()
                            .setTaskId(taskId)
                            .setTeachingClassName(excelSubClassNoVo.getClassName() + course.getCourseName() + "(单)")
                            .setCourseId(course.getCourseId())
                            .setCourseName(course.getCourseName())
                            .setStudyNature(course.getCourseNature())
                            .setMajorProp(course.getMajorProp())
                            .setClassNum(studentList.size() / 2)
                            .setBaseMajorId(studentList.get(0).getMajorId())
                            .setMajorName(studentList.get(0).getMajorName())
                            .setBaseCollegeId(studentList.get(0).getBaseCollegeId())
                            .setCollegeName(studentList.get(0).getCollegeName())
                            .setGradeId(studentList.get(0).getGradeId())
                            .setGradeName(studentList.get(0).getGradeName())
                            .setTeachingClassType(0)
                            .setFlag(1)
                            .setCampusId(majorGrade.getCampusId())
                            .setCampusName(majorGrade.getCampusName())
                            .setSplitClassUuid(uuid.toString())
                            .setIsSingle(1);
                    teachingClassService.save(singleClass);
                    classList.add(singleClass);
                    //单班教学班学生
                    singleStu.forEach(a -> {
                        teachingClassStudentList.add(new TeachingClassStudent()
                                .setFlag(1)
                                .setTeachingClassId(singleClass.getTeachingClassId())
                                .setCourseId(course.getCourseId())
                                .setStudentId(a.getStudentId()));
                    });

                    TeachingClass doubleClass = new TeachingClass()
                            .setTaskId(taskId)
                            .setTeachingClassName(excelSubClassNoVo.getClassName() + course.getCourseName() + "(双)")
                            .setCourseId(course.getCourseId())
                            .setCourseName(course.getCourseName())
                            .setCourseName(course.getCourseName())
                            .setStudyNature(course.getCourseNature())
                            .setClassNum(studentList.size() / 2)
                            .setBaseMajorId(studentList.get(0).getMajorId())
                            .setMajorName(studentList.get(0).getMajorName())
                            .setBaseCollegeId(studentList.get(0).getBaseCollegeId())
                            .setCollegeName(studentList.get(0).getCollegeName())
                            .setGradeId(studentList.get(0).getGradeId())
                            .setGradeName(studentList.get(0).getGradeName())
                            .setTeachingClassType(0)
                            .setFlag(1)
                            .setCampusId(majorGrade.getCampusId())
                            .setCampusName(majorGrade.getCampusName())
                            .setSplitClassUuid(uuid.toString())
                            .setIsSingle(2);
                    teachingClassService.save(doubleClass);
                    classList.add(doubleClass);
                    //双班教学班学生
                    doubleStu.forEach(a -> {
                        teachingClassStudentList.add(new TeachingClassStudent()
                                .setFlag(1)
                                .setTeachingClassId(doubleClass.getTeachingClassId())
                                .setCourseId(course.getCourseId())
                                .setStudentId(a.getStudentId()));
                    });
                }
                //教学班参数
                List<TeachingClassWeek> allTeachingClassWeeks = teachingClassService.initTeachingClassWeek(classList);

                List<TeachingClassTeacher> teachingClassTeachers = new ArrayList<>();


                classList.forEach(c -> {
                    List<TeachingClassWeek> teachingClassWeeks = allTeachingClassWeeks.stream().filter(p -> p.getTeachingClassId().equals(c.getTeachingClassId())).collect(Collectors.toList());

                    ExcelSubClassNoVo excelSubClassNoVo1 = value.stream().filter(p -> p.getCourseName().equals(c.getCourseName()) && p.getFlag().equals(c.getIsSingle())).findFirst().orElse(null);
                    teachingClassWeeks.forEach(tw -> {
                        tw.setRoomType(roomMap.get(excelSubClassNoVo1.getRoom()).getRoomType());
                        tw.setRoomName(roomMap.get(excelSubClassNoVo1.getRoom()).getRoomName());
                        tw.setRoomId(roomMap.get(excelSubClassNoVo1.getRoom()).getRoomId());
                        tw.setRoomTypeName(roomMap.get(excelSubClassNoVo1.getRoom()).getRoomTypeName());

                        if (StringUtils.isNotBlank(excelSubClassNoVo1.getTeacherNo())) {

                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(c.getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teacherMap.get(excelSubClassNoVo1.getTeacherNo()).getTeacherId());
                            teachingClassTeacher.setHourType(tw.getHourType());
                            teachingClassTeachers.add(teachingClassTeacher);
                        }

                        if (StringUtils.isNotBlank(excelSubClassNoVo1.getAssTeacherNo())) {

                            TeachingClassTeacher teachingClassTeacher = new TeachingClassTeacher();
                            teachingClassTeacher.setTeachingClassId(c.getTeachingClassId());
                            teachingClassTeacher.setTeacherId(teacherMap.get(excelSubClassNoVo1.getAssTeacherNo()).getTeacherId());
                            teachingClassTeacher.setHourType(tw.getHourType());
                            teachingClassTeachers.add(teachingClassTeacher);
                        }
                    });
                });


                Consumer<List<TeachingClassWeek>> teachingClassWeekConsumer = o -> teachingClassWeekMapper.addBatch(o);
                BatchInsert.batchSplitInsert(allTeachingClassWeeks, teachingClassWeekConsumer);
                //批量插入教学班学生，大数据批量插入
                Consumer<List<TeachingClassStudent>> studentConsumer = o -> teachingClassStudentMapper.addBatch(o);
                BatchInsert.batchSplitInsert(teachingClassStudentList, studentConsumer);

                teachingClassTeacherService.saveOrUpdateBatch(teachingClassTeachers);


                SplitClass spiltClass = new SplitClass();
                spiltClass.setClassId(studentList1.get(0).getClassId());
                spiltClass.setClassName(studentList1.get(0).getClassName());
                spiltClass.setCourseId(courseIds.stream().map(String::valueOf).collect(Collectors.joining(",")));
                spiltClass.setCourseName(String.join(",", courseNames));
                spiltClass.setGradeId(studentList1.get(0).getGradeId());
                spiltClass.setGradeName(studentList1.get(0).getGradeName());
                spiltClass.setSplitClassUuid(uuid.toString());
                spiltClass.setSplitName(excelSubClassNoVo.getTeachingClassName());
                spiltClass.setTaskId(taskId);
                splitClassService.saveOrUpdate(spiltClass);
            }
        }


    }

    @Override
    public void exportTeachingClassCourse(HttpServletResponse response, Integer taskId, Long courseId) {


        List<ExcelTeachingClassCourse> excelTeachingClassCourses = new ArrayList<>();

        List<TeachingClass> teachingClasses = teachingClassService.lambdaQuery().eq(TeachingClass::getTaskId, taskId).eq(ObjUtil.isNotNull(courseId), TeachingClass::getCourseId, courseId).list();

        if (CollUtil.isNotEmpty(teachingClasses)) {

            List<Long> tIds = teachingClasses.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());

            List<TeachingClassWeek> teachingClassWeeks = teachingClassWeekService.lambdaQuery().in(TeachingClassWeek::getTeachingClassId, tIds).list();
            List<TeachingClassTeacher> teachingClassTeachers = teachingClassTeacherService.lambdaQuery().in(TeachingClassTeacher::getTeachingClassId, tIds).list();

            List<TeachingClassStudent> teachingClassStudents = teachingClassStudentService.lambdaQuery().in(TeachingClassStudent::getTeachingClassId, tIds).eq(TeachingClassStudent::getFlag, 1).list();

            List<Teacher> teachers = new ArrayList<>();
            if (CollUtil.isNotEmpty(teachingClassTeachers)) {
                List<Long> teacherIds = teachingClassTeachers.stream().map(TeachingClassTeacher::getTeacherId).distinct().collect(Collectors.toList());
                teachers = teacherService.lambdaQuery().eq(Teacher::getTaskId, taskId).in(Teacher::getTeacherId, teacherIds).list();
            }


            for (TeachingClass teachingClass : teachingClasses) {
                ExcelTeachingClassCourse excelTeachingClassCourse = new ExcelTeachingClassCourse();

                excelTeachingClassCourse.setCourseName(teachingClass.getCourseName());
                excelTeachingClassCourse.setCollegeName(teachingClass.getCollegeName());
                excelTeachingClassCourse.setTeachingClassName(teachingClass.getTeachingClassName());
                excelTeachingClassCourse.setCampusName(teachingClass.getCampusName());
                excelTeachingClassCourse.setFlag(teachingClass.getFlag().equals(1) ? "课程" : "环节");

                long count = teachingClassStudents.stream().filter(p -> p.getTeachingClassId().equals(teachingClass.getTeachingClassId())).count();
                excelTeachingClassCourse.setStudentNum((int) count);
                excelTeachingClassCourse.setAssessmentMethod(teachingClass.getAssessmentName());
                List<TeachingClassWeekExcelDto> teachingClassWeekExcelDtos = new ArrayList<>();
                List<TeachingClassWeek> teachingClassWeekList = teachingClassWeeks.stream().filter(p -> p.getTeachingClassId().equals(teachingClass.getTeachingClassId())).collect(Collectors.toList());
                for (TeachingClassWeek teachingClassWeek : teachingClassWeekList) {
                    TeachingClassWeekExcelDto teachingClassWeekExcelDto = new TeachingClassWeekExcelDto();
                    List<TeachingClassTeacher> teachers1 = teachingClassTeachers.stream().filter(p -> p.getTeachingClassId().equals(teachingClass.getTeachingClassId()) && p.getHourType().equals(teachingClassWeek.getHourType())).collect(Collectors.toList());
                    List<Teacher> teachers2 = teachers.stream().filter(p -> teachers1.stream().anyMatch(o -> o.getTeacherId().equals(p.getTeacherId())) && p.getIdentity().equals(1)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teachers2)) {
                        String teacherName = teachers2.stream().map(Teacher::getTeacherName).collect(Collectors.joining(","));
                        teachingClassWeekExcelDto.setTeacherNo(teacherName);
                    }

                    List<Teacher> teachers3 = teachers.stream().filter(p -> teachers1.stream().anyMatch(o -> o.getTeacherId().equals(p.getTeacherId())) && p.getIdentity().equals(2)).collect(Collectors.toList());
                    if (CollUtil.isNotEmpty(teachers3)) {
                        String teacherName = teachers3.stream().map(Teacher::getTeacherName).collect(Collectors.joining(","));
                        teachingClassWeekExcelDto.setAssTeacherNo(teacherName);
                    }
                    teachingClassWeekExcelDto.setHourType(teachingClassWeek.getHourType().equals(1) ? "讲授" :
                            teachingClassWeek.getHourType().equals(2) ? "实验" : teachingClassWeek.getHourType().equals(3) ? "上机" : "其他");

                    teachingClassWeekExcelDto.setRoomType(teachingClassWeek.getRoomTypeName());
                    teachingClassWeekExcelDto.setRoom(teachingClassWeek.getRoomName());

                    teachingClassWeekExcelDto.setWeekNum(teachingClassWeek.getWeekNum());
                    teachingClassWeekExcelDto.setConnectNumber(teachingClassWeek.getConnectNumber());
                    teachingClassWeekExcelDto.setConnectSection(teachingClassWeek.getConnectSection());


                    if (StringUtils.isNotBlank(teachingClassWeek.getWeek())) {
                        char[] chars = teachingClassWeek.getWeek().toCharArray();
                        int num = 0;
                        StringBuilder sb = new StringBuilder();
                        for (int i = 0; i < chars.length; i++) {
                            if (chars[i] == '1') {
                                sb.append((i + 1) + ",");
                                num++;
                            }
                        }
                        String s = sb.toString();
                        s = s.substring(0, s.length() - 1) + "周";

                        teachingClassWeekExcelDto.setTotalHour(num * teachingClassWeek.getWeekNum());
                        teachingClassWeekExcelDto.setWeek(s);
                    }

                    teachingClassWeekExcelDtos.add(teachingClassWeekExcelDto);
                }
                excelTeachingClassCourse.setTeachingClassWeekExcelVoList(teachingClassWeekExcelDtos);
                excelTeachingClassCourses.add(excelTeachingClassCourse);
            }
        }


        excelTeachingClassCourses = excelTeachingClassCourses.stream().sorted(Comparator.comparing(ExcelTeachingClassCourse::getTeachingClassName)).collect(Collectors.toList());


        TaskInfo taskInfo = taskInfoService.getById(taskId);

        Course course = courseService.getById(courseId);
        //构建标题
        String title = " {} {} {}教学班信息导出";
        String format = StrUtil.format(title, taskInfo.getTermName(), taskInfo.getSchoolName(), course.getCourseName());


        String time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy_MM_dd_HH_mm_ss"));

        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel; charset=utf-8");

        MyExcelUtils.exportExcel(excelTeachingClassCourses,
                format,
                "教学班信息导出",
                ExcelTeachingClassCourse.class,
                "教学班信息导出" + time + ".xls", response);
    }

    private List<ExcelSubClassNoVo> readImportSubClass(MultipartFile file) {


        List<ExcelSubClassNoVo> excelTeachingActivities = new ArrayList<>();
        List<String> expectedHeaders = Arrays.asList(
                "教学班名称", "行政班名称", "单双班标识", "课程名称", "任课老师工号", "任课教师", "助教教师工号", "助教教师", "上课场地");
        try {

            InputStream inputStream = file.getResource().getInputStream();
            ExcelReader reader = ExcelUtil.getReader(inputStream, 0);
            //读取表头 判断是否符合预期
            List<String> actualHeaders = reader.readRow(1).stream()
                    .map(Object::toString).filter(org.apache.commons.lang3.StringUtils::isNotBlank)
                    .collect(Collectors.toList());
            if (!expectedHeaders.equals(actualHeaders)) {
                throw new BizException(5, "导入模板不匹配，请按照标准模板编辑后导入");
            }

            reader.addHeaderAlias("教学班名称", "teachingClassName");
            reader.addHeaderAlias("行政班名称", "className");
            reader.addHeaderAlias("单双班标识", "flag");
            reader.addHeaderAlias("课程名称", "courseName");
            reader.addHeaderAlias("任课老师工号", "teacherNo");
            reader.addHeaderAlias("任课老师", "teacher");
            reader.addHeaderAlias("助教教师工号", "assTeacherNo");
            reader.addHeaderAlias("助教教师", "assTeacher");
            reader.addHeaderAlias("上课场地", "room");

            excelTeachingActivities = reader.read(1, 2, ExcelSubClassNoVo.class);
            reader.close();
        } catch (Exception ex) {
            log.info("excel导入教学任务失败:{}", ex.getMessage());
        }

        if (excelTeachingActivities.size() == 0) {
            throw new BizException(5, "导入数据为空，请检查后重新导入");
        }

        return excelTeachingActivities;
    }
}
